我有一个元组列表,元组中的两个项目之一是一个数字,我试图得到所有元组的列表,这些数字的总和将是一个特定的总和。使用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) ]
这是只对数字的正确结果,我不知道如何对元组得到类似的结果。 先谢谢你
我将列出理解列表,以便更容易地遵循代码流程
所以我们可以看到每个seq都有我们想要的——元组对。现在需要测试第二个元素的和是否为5
相关问题 更多 >
编程相关推荐