Python与元组的组合

2024-09-29 21:20:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,元组中的两个项目之一是一个数字,我试图得到所有元组的列表,这些数字的总和将是一个特定的总和。使用itertools组合,我只得到数字列表,而不是元组列表:

listInit= [("A",1), ("B",2),("C",3),("D",4)]

resultExpected=[ [("A",1),("D",4)], [("B",2),("C",3)] ] #target sum=5

使用以下代码:

listInit=[1,2,3,4]
result=[seq for i in range(len(listInit), 0, -1) for seq in itertools.combinations(listInit, i) if sum(seq) == 5]
print(result)

我得到:

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

这是只对数字的正确结果,我不知道如何对元组得到类似的结果。 先谢谢你


Tags: 项目代码intarget列表for数字result
1条回答
网友
1楼 · 发布于 2024-09-29 21:20:43

我将列出理解列表,以便更容易地遵循代码流程

for seq in itertools.combinations(listInit, 2):
    print(seq)

=== Output: ===
(('A', 1), ('B', 2))
(('A', 1), ('C', 3))
(('A', 1), ('D', 4))
(('B', 2), ('C', 3))
(('B', 2), ('D', 4))
(('C', 3), ('D', 4))

所以我们可以看到每个seq都有我们想要的——元组对。现在需要测试第二个元素的和是否为5

for seq in itertools.combinations(listInit, 2):
    # seq is a tuple of tuples
    # so you want the second element of both outer tuples
    if seq[0][1] + seq[1][1] == 5:
        print(seq)

=== Output: ===
(('A', 1), ('D', 4))
(('B', 2), ('C', 3))

相关问题 更多 >

    热门问题