執行時我需要以下代碼來生成一個固定長度為 4 個元素的串列。為什么它不適用于 for 回圈?
from random import choice
pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = []
for pulled_ticket in range(4):
pulled_ticket = choice(pool)
if pulled_ticket not in winning_ticket:
winning_ticket.append(pulled_ticket)
print(winning_ticket)
當我執行代碼時,結果如下所示:
[7, 4, 8, 'e']
[5, 'e']
['e', 6, 3]
但是使用while回圈,我沒有這個問題:
from random import choice
pool = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'a', 'b', 'c', 'd', 'e']
winning_ticket = []
while len(winning_ticket) < 4:
pulled_ticket = choice(pool)
if pulled_ticket not in winning_ticket:
winning_ticket.append(pulled_ticket)
print(winning_ticket)
串列長度始終為四:
['e', 5, 1, 8]
[7, 'd', 2, 8]
[2, 6, 'e', 10]
非常感謝!
uj5u.com熱心網友回復:
主要問題就像我在評論中所說的那樣,您的 for 回圈只進行 4 次迭代。當您的 while 回圈繼續進行時,直到達到的長度為 4。
示例輸出:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
[4, 8, 'a']
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
Iteration: 6
[9, 6, 'a', 'b']
您可以看到 for 回圈在執行 4 次傳遞時為您提供了一個 3 大小的串列,這意味著一旦它遇到相同的亂數。一種更簡單的方法是使用選項,例如@norie,bc 您可以指定回傳串列的大小,并且不需要回圈。
print(choices(pool, k=4))
['a', 8, 'd', 8]
uj5u.com熱心網友回復:
使用時非常合乎邏輯的答案for pulled_ticket in range(4):將觸發choice然后if 4次,如果您選擇兩次相同的數字,它將不會被添加,您將在串列中完成3 個專案
while loop 等待有4 個專案,所以如果它多次獲得相同的選擇,它將繼續
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441607.html
上一篇:瞄準由豎線分隔的單詞Python
下一篇:從串列集合中洗掉串列
