2 回答

TA貢獻1862條經驗 獲得超7個贊
看看迭代工具
中的組合
。
>>> 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))

TA貢獻1842條經驗 獲得超13個贊
試試這個代碼:
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)
添加回答
舉報