簡體   English   中英

在 Itertools 產品期間從組合中刪除項目

[英]Remove Items from Combination during Itertools Product

我知道之前有人問過這個問題,但我找不到適合我問題的解決方案:

  • 我有一個可以出現在六個位置的人的列表(沒有重復)。
  • 我使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM