【问题标题】:summing same numbers of different lists into another list将相同数量的不同列表相加到另一个列表中
【发布时间】:2022-01-26 12:31:21
【问题描述】:

#现在我知道有更简单的方法,但我需要在#function 中实现它,这是我的尝试。现在它不起作用,但你能#help我吗?

def intersection(l1, l2):
    l3 = []
    for x in range(0, len`length `(l1)):
        if x == l2:
            l3.append(x)
    return l3

print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))

【问题讨论】:

  • 现在它不起作用更具体。告诉我们程序实际上做了什么,并说明它与您想要的有何不同。

标签: python list function sum append


【解决方案1】:

你可以使用 numpy 的 np.intersect1d 方法。

import numpy as np
def intersection(l1, l2):
    return np.intersect1d(l1,l2).tolist()
print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))

输出:

[1, 4]

【讨论】:

    【解决方案2】:

    您正在尝试迭代从 0 到 len(l1) 的整数,而不是迭代列表项。你应该使用

    for x in l1:
    

    而不是

    for x in range(0, len`length `(l1)):
    

    您在比较项目时也有错误。你应该使用:

    if x in l2:
    

    而不是

    if x == l2:
    

    完整代码示例:

    def intersection(l1, l2):
        l3 = []
        for x in l1:
            if x in l2:
                l3.append(x)
        return l3
    
    print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))
    

    【讨论】:

    • 非常感谢
    • 很高兴为您提供帮助,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受。
    【解决方案3】:

    最好/最快的方法是使用set.intersection

    def intersection(l1, l2):
         return set(l1).intersection(l2)
    

    【讨论】:

    • 非常感谢
    【解决方案4】:

    您需要同时迭代两个列表,将每对相加并将其放入新列表中。

    def intersection(l1, l2):
        result = []
        for item1, item2 in zip(l1, l2):
            result.append(item1 + item2)
        return result
    
    print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))
    
    
    

    【讨论】:

    • 非常感谢
    • @DarthVader63 很高兴为您提供帮助,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受并投票。
    猜你喜欢
    • 2022-01-04
    • 1970-01-01
    • 2013-03-25
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    相关资源
    最近更新 更多