簡體   English   中英

從排列中清除元組列表

[英]Clean a list of tuples from the permutations

我有一個我生成的元組列表:

frequencies = [(a, b, 40) for a in [x for x in range(20, 110, 10) if x != 90] for b in range(20, 90, 10)]\
+[(a, b, 40) for a in [x for x in range(20, 110, 10) if x != 90] for b in range(100, 175, 25)]\
+[(a, b, 40) for a in [x for x in range(20, 110, 10) if x != 90] for b in range(200, 400, 50)]

我想考慮排列sa(20,60,40)和(60,20,40)相同,所以只保留其中一個。

我目前的做法是:

# Clean permutations
frequencies2 = list()
for f in frequencies:
    possible = list(itertools.permutations(f))
    if len([p for p in possible if p in frequencies2]) == 0:
        frequencies2.append(f)

frequencies = frequencies2

我確信有更好的方法可以做到這一點,但我找不到它。 雖然這段代碼不是很美觀,但只有O(n²)。

謝謝你的幫助。

如果要在生成完成后過濾掉排列,則可以簡單地對元組進行排序並進行比較:

without_permutations = list({tuple(sorted(f)): f for f in frequencies}.values())

這構建了一個dict,其中排序的元組指向原始元組。 這樣,后來的元組將覆蓋自己的早期排列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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