[英]Remove Items from Combination during Itertools Product
我知道之前有人問過這個問題,但我找不到適合我問題的解決方案:
當前代碼:
for combination in itertools.product(nameList1,nameList2,nameList3,nameList4,nameList5,nameList6):
nameofPlayer1 = combination[0]
nameofPlayer2 = combination[1]
etc.
然后:
if nameofPlayer1 == nameofPlayer2:
continue
if nameofPlayer1 == nameofPlayer3:
continue
etc.
我現在想做的是:
if timesUsedPlayer1 > xyz:
#remove Player1 from nameList1, nameList2, etc.
我相信這會加速后續迭代,因為即使組合最終會失敗(因為我有其他觸發器來檢查某人被使用了多少次),我可以通過將此人排除在外來完全切斷“檢查”迭代。
提前致謝!
下面的代碼顯示了一種在itertools
中使用permutations()
從問題中提到的人員列表中生成所有可能的 6 個名稱序列的方法,這樣一個名稱可能會被刪除並且不再考慮處理。
numPrints = 0
nameList = [
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"
]
dropped = set()
for combination in itertools.permutations(nameList, 6):
for name in combination:
# this simulates the condition that would lead to removal of a name from further consideration
if name in ["b", "c", "d", "e", "f"]:
dropped.add(name)
combSet = set(combination)
if not combSet.isdisjoint(dropped):
# the combination contains a name that has been dropped, so ignore it
continue
# process the combination here
if numPrints < 10:
print(f"processing {combination}")
numPrints += 1
if numPrints == 10:
print("etc.")
上例為 Output:
processing ('a', 'g', 'h', 'i', 'j', 'k')
processing ('a', 'g', 'h', 'i', 'k', 'j')
processing ('a', 'g', 'h', 'j', 'i', 'k')
processing ('a', 'g', 'h', 'j', 'k', 'i')
processing ('a', 'g', 'h', 'k', 'i', 'j')
processing ('a', 'g', 'h', 'k', 'j', 'i')
processing ('a', 'g', 'i', 'h', 'j', 'k')
processing ('a', 'g', 'i', 'h', 'k', 'j')
processing ('a', 'g', 'i', 'j', 'h', 'k')
processing ('a', 'g', 'i', 'j', 'k', 'h')
etc.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.