繁体   English   中英

如何查找列表中每个元素的总和

[英]How to find the sum of each element in a list with each other element

我需要编写一个函数,在该函数中,对于任何列表,列表中的每个元素都将加在一起,以查看其是否等于常量。

例如:

L = [1, 2, 3, 4]

每个元素加在一起的总和是1+2=3 1+3=4 1+4=5 2+3=5 2+4=6 3+4=7

然后将这些结果中的每一个测试为常数,例如,如果output = C,其中C = 3 ,然后将求和等于常数的两个数字附加到要打印的新列表中。

我不允许在这里使用索引。

到目前为止,我能够沿列表成对添加数字:

def prize(L):
    possible = []
    C = 4
    prevprev = L.pop(0)
    prev = L.pop(0)
    print("initial", prevprev, prev)

    for n in L:
        i = prev + prevprev
        prevprev = prev
        prev = L.pop(0)


    if i == C:
        possible.append(i)

    return possible

print("possible ", possible)

但是由于某种原因,在迭代时会错过列表中的最后2个元素。

我不太了解您的代码或解释,但是我相信这可以满足您的要求。 无需itertools模块即可完成此操作。 使用它会产生更紧凑的代码。 这是itertools的替代方法

lst = [1, 2, 3, 4]

def prize(L):
    pair_list = []
    C = 4

    # Creates a list of tuples (1, 2), (1, 3), etc
    for x in L:
        for y in L:
            # if x != y | To prevent 1 + 1 and 2 + 2 (following example)
            # (y, x) not in pair_list | Prevent inverted pairs
            if x != y and x + y == C and (y, x) not in pair_list:
                pair_list.append((x, y))

    # Return list tuples that add to constant           
    return pair_list

print('Possible', prize(lst))

如果您想使用itertools,则可以使用

from itertools import combinations

def prize(L):
    C = 4
    return [(x, y) for x, y in combinations(L, 2) if x + y == C]

lst = [1, 2, 3, 4]

print('Possible', prize(lst))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM