猿问

打印元素列表对的所有可能组合

我有一个python中的元组列表。


list = [(1,2), (1,3), (1,4), (2,3), (2, 4), (3,4)]

如何打印所有可能的元组对?我想避免重复。例如 ,(1,2)、(2,3) 和 (2,3)、(1,2) 是重复的。


预期结果是:


(1,2), (1,3)

(1,2), (1,4)

(1,2), (2,3)

(1,2), (2,4)

(1,2), (3,4)

(1,3), (1,4)

(1,3), (2,3)

(1,3), (2,4)

(1,3), (3,4)

(1,4), (2,3)

(1,4), (2,4)

(1,4), (3,4)

(2,3), (2,4)

(2,3), (3,4)

(2,4), (3,4)


郎朗坤
浏览 70回答 2
2回答

牧羊人nacy

看看迭代工具中的组合。>>> l = [(1,2), (1,3), (1,4), (2,3), (2, 4), (3,4)]>>> import itertools>>> combinations = itertools.combinations(l, 2)>>> for combination in combinations:...   print(combination)...((1, 2), (1, 3))((1, 2), (1, 4))((1, 2), (2, 3))((1, 2), (2, 4))((1, 2), (3, 4))((1, 3), (1, 4))((1, 3), (2, 3))((1, 3), (2, 4))((1, 3), (3, 4))((1, 4), (2, 3))((1, 4), (2, 4))((1, 4), (3, 4))((2, 3), (2, 4))((2, 3), (3, 4))((2, 4), (3, 4))

红颜莎娜

试试这个代码:from itertools import combinations # Get all combinations and length 2 comb = combinations([(1,2), (1,3), (1,4), (2,3), (2, 4), (3,4)], 2) # Print the obtained combinations for i in list(comb):     print(i[0],",", i[1])输出:(1, 2) , (1, 3)(1, 2) , (1, 4)(1, 2) , (2, 3)(1, 2) , (2, 4)(1, 2) , (3, 4)(1, 3) , (1, 4)(1, 3) , (2, 3)(1, 3) , (2, 4)(1, 3) , (3, 4)(1, 4) , (2, 3)(1, 4) , (2, 4)(1, 4) , (3, 4)(2, 3) , (2, 4)(2, 3) , (3, 4)(2, 4) , (3, 4)
随时随地看视频慕课网APP

相关分类

Python
我要回答