python随机显示_显示随机选择(Python)

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.

list1 = item1, item2, item3, item4,

item5, item6, item7, item8, item9,

item 10

Display a random selection

from the list above

list2 = store the last displayed item in list2 which should only store 7

items, not more

Display a random

selection from the list but make

sure it doesn't exist in the

list2

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?

Thanks

解决方案

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)

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.

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值