[英]Get all pairwise combinations from a list
例如,如果輸入列表是
[1, 2, 3, 4]
我希望輸出是
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
如果可能,我想要一個比使用兩個 for 循環的蠻力方法更好的解決方案。 我該如何實施?
盡管前面的答案會為您提供所有成對排序,但示例預期結果似乎暗示您想要所有無序對。
這可以通過itertools.combinations
完成:
>>> import itertools
>>> x = [1,2,3,4]
>>> list(itertools.combinations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
與另一個結果比較:
>>> list(itertools.permutations(x, 2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
import itertools
x = [1,2,3,4]
for each in itertools.permutations(x,2):
print(each)
請注意, itertools 是一個生成器對象,這意味着您需要遍歷它以獲取您想要的所有內容。 '2' 是可選的,但它告訴函數你想要的每個組合的數字是多少。
編輯:
正如 ForceBru 在評論中所說,您可以解壓生成器進行打印,一起跳過 for 循環但我仍然會遍歷它,因為您可能不知道生成的對象有多大:
print(*itertools.permutations(x, 2))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.