簡體   English   中英

從列表中獲取所有成對組合

[英]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.

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