亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

打印元素列表對的所有可能組合

打印元素列表對的所有可能組合

郎朗坤 2022-09-06 16:24:10
我有一個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)
查看完整描述

2 回答

?
牧羊人nacy

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))


查看完整回答
反對 回復 2022-09-06
?
紅顏莎娜

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)


查看完整回答
反對 回復 2022-09-06
  • 2 回答
  • 0 關注
  • 99 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號