为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

郎朗坤 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条经验 获得超12个赞

试试这个代码:


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 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信