1
a = [1,2,3,4,5,6,7]
b  = [56,59,62,65,67,69]


def sumOfTwo(a,b,v):
    for i in range (len(a)):
        val_needed = v - a[i]
        for j in range (len(b)):
            if b[j] == val_needed:
                x = b[j]
                y = a[i]             
    print(x,y) 

sumOfTwo(a,b,v=70)

输出:5 65

如果问题中的给定列表中可能有更多对,我该怎么做?帮助。还有什么方法可以实现这一目标?

4

2 回答 2

3

如果您只想打印匹配的值,您只需要将 print 语句缩进到 中if,如下所述。此外,您应该对循环和变量分配使用更Pythonic的方法。for

a = [1,2,3,4,5,6,7]
b  = [56,59,62,65,67,69]


def sumOfTwo(a,b,v):
    for i in a:
        val_needed = v - i
        for j in b:
            if j == val_needed:
                x, y = j, i
                print(x,y)

sumOfTwo(a,b,v=70)
于 2020-02-21T16:47:36.367 回答
2

使用列表推导:

a = [1,2,3,4,5,6,7]
b = [56,59,62,65,67,69]

c = [(x, y)
     for x in a
     for y in b
     if x + y == 70]

print(c)

这产生

[(1, 69), (3, 67), (5, 65)]
于 2020-02-21T16:54:17.783 回答