显示随机选择(Python) [英] Display random choice (Python)

查看:137
本文介绍了显示随机选择(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要随机显示的项目的列表[],但是在最近的x个请求中,显示的项目不得重复多次.

I have a list[] of items from which I'd like to display one randomly, but the displayed item must not repeat more than once in last x requests.

  1. list1 = item1,item2,item3,item4, item5,item6,item7,item8,item9, 项目10
  2. 显示随机选择 从上面的列表
  3. list2 =将最后显示的项目存储在list2中,该项目仅应存储7 项,而不是更多
  4. 随机显示 从列表中选择,但使 确保它不存在 list2
  1. list1 = item1, item2, item3, item4, item5, item6, item7, item8, item9, item 10
  2. Display a random selection from the list above
  3. list2 = store the last displayed item in list2 which should only store 7 items, not more
  4. Display a random selection from the list but make sure it doesn't exist in the list2

这是正确的方法吗?无论哪种方式,我都想知道如何将列表限制为仅存储7个项目?

Is that the right way to do it? Either way, I'd like to know how to limit a list to store only 7 items?

谢谢

推荐答案

collections.deque是python中唯一自然支持绑定的序列类型(并且仅在python 2.6及更高版本中.)如果使用python 2.6或更高版本:

collections.deque is the only sequence type in python that naturally supports being bounded (and only in Python 2.6 and up.) If using python 2.6 or newer:

# Setup
from collections import deque
from random import choice
used = deque(maxlen=7)

# Now your sampling bit
item = random.choice([x for x in list1 if x not in used])
used.append(item)

如果使用python 2.5或更低版本,则不能使用maxlen参数,并且将需要执行另一项操作以切断双端队列的前端:

If using python 2.5 or less, you can't use the maxlen argument, and will need to do one more operation to chop off the front of the deque:

while len(used) > 7:
    used.popleft()

这并不是最有效的方法,但是它可以工作.如果需要速度,并且对象是可哈希的(大多数不可变的类型),请考虑使用字典作为已用"列表.

This isn't exactly the most efficient method, but it works. If you need speed, and your objects are hashable (most immutable types), consider using a dictionary instead as your "used" list.

此外,如果只需要执行一次,则random.shuffle方法也可以使用.

Also, if you only need to do this once, the random.shuffle method works too.

这篇关于显示随机选择(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆