我有一個列表[]我想隨機顯示一個項目,但顯示的項目在最後的x個請求中不能重複多次。顯示隨機選擇(Python)
- list1的= ITEM1,ITEM2,項目3,ITEM4, ITEM5,ITEM6,item7,item8,item9, 項目10
- 顯示從上述列表中
- list2中=存儲中的最後一個隨機選擇 在列表2顯示項目只應店7個 項目,而不是更多
- 顯示從列表中隨機選擇 但要 確保它不會在 list2中存在
這是正確的做法嗎?無論哪種方式,我想知道如何限制列表只存儲7個項目?
謝謝
我有一個列表[]我想隨機顯示一個項目,但顯示的項目在最後的x個請求中不能重複多次。顯示隨機選擇(Python)
這是正確的做法嗎?無論哪種方式,我想知道如何限制列表只存儲7個項目?
謝謝
collections.deque是在自然地支持定界蟒的唯一序列類型(並且僅在Python 2.6和最多)。如果使用python 2.6或更新:
# 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參數,將需要做一個更多操作砍掉了雙端隊列的前面:
while len(used) > 7:
used.popleft()
這不正是最有效的方法,但它的作品。如果你需要速度,並且你的對象是可散列的(大多數不可變的類型),可以考慮使用一個字典作爲你的「已用」列表。
另外,如果你只需要做一次,那麼random.shuffle方法也可以。
有關deque的瞭解,謝謝!:) – 3zzy 2010-01-06 08:47:22
這是你想要的嗎?
list1 = range(10)
import random
random.shuffle(list1)
list2 = list1[:7]
for item in list2:
print item
print list1[7]
換句話說,看看random.shuffle()
。如果您想保持原始列表完好無損,您可以複製它:list_copy = list1[:]
。
object = random.shuffle(list1)返回None,它不能將值存儲在一個對象中嗎? – 3zzy 2010-01-06 08:31:11
不,'random.shuffle()'就地修改列表(這就是爲什麼要複製的原因)。你可以通過'random.choice()'從列表中獲得一個隨機項目。 – 2010-01-06 08:35:22
喜歡的東西:
# Setup
import random
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = []
# Loop for as long as you want to display items
while loopCondition:
index = random.randint(0, len(list1)-1)
item = list1.pop(index)
print item
list2.append(item)
if(len(list2) > 7):
list1.append(list2.pop(0))
*無限循環*僅用於演示我猜? – 2010-01-06 08:19:36
絕對如此。 Nimbuz指出他有一些「請求」進來,所以我只是將它表示爲一個無限循環。我會修改,以免有人真的把它放進去。:) – Sapph 2010-01-06 08:27:36
你可以嘗試使用發電機的功能,並呼籲.next()
每當你需要一個新的項目。
import random
def randomizer(l, x):
penalty_box = []
random.shuffle(l)
while True:
element = l.pop(0)
# for show
print penalty_box, l
yield element
penalty_box.append(element)
if len(penalty_box) > x:
# penalty time over for the first element in the box
# reinsert randomly into the list
element = penalty_box.pop(0)
i = random.randint(0, len(l))
l.insert(i, element)
用例:
>>> r = randomizer([1,2, 3, 4, 5, 6, 7, 8], 3)
>>> r.next()
[] [1, 5, 2, 6, 4, 8, 7]
3
>>> r.next()
[3] [5, 2, 6, 4, 8, 7]
1
>>> r.next()
[3, 1] [2, 6, 4, 8, 7]
5
>>> r.next()
[3, 1, 5] [6, 4, 8, 7]
2
>>> r.next()
[1, 5, 2] [4, 3, 8, 7]
6
>>> r.next()
[5, 2, 6] [4, 3, 8, 7]
1
>>> r.next()
[2, 6, 1] [5, 3, 8, 7]
4
>>> r.next()
[6, 1, 4] [3, 8, 2, 7]
5
我會用一組對象來獲得在列表2 List1中的項目清單,但並不:
import random
list1 = set(["item1", "item2", "item3", "item4", "item5",
"item6", "item7", "item8", "item9", "item10"])
list2 = []
while True: # Or something
selection = random.choice(tuple(list1.difference(set(list2))))
print(selection)
list2.append(selection)
if len(list2) > 7:
list2 = list2[-7:]
重複:HTTP://計算器。 COM /問題/ 1058712 /如何-DO-I-選擇 - 一個隨機元素從 - 一個陣列式-蟒。可能是家庭作業。 – 2010-01-06 11:11:05