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
I'd use set objects to get a list of items in list1 but not in list2:
Something like:
You could try using a generator function and call
.next()
whenever you need a new item.Usage example:
Is this what you want?
In other words, look at
random.shuffle()
. If you want to keep the original list intact, you can copy it:list_copy = list1[:]
.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:
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:
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.