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.