【问题标题】:Take two list of lists and returns a new list of lists which is the sum of the values at the matching index positions? [closed]取两个列表并返回一个新的列表列表,它是匹配索引位置的值的总和? [关闭]
【发布时间】:2019-04-06 01:31:30
【问题描述】:

我正在尝试创建一个函数,该函数接受两个列表并返回它们的值的总和。

假设我有 2 个列表:

list1 = [[7,8], []]
list2 = [[3,4,2],[6,9]]

预期输出:

[[10,12,2],[6,9]]

或另外 2 个列表:

list1 = [[], []]
list2 = [[3,4,2],[6,9]]

预期输出:

[[3,4,2],[6,9]] 

我认为使用列表推导是实现此目的最有效的方法,但我对列表推导并不像我想的那样熟悉。

我查看了 Stack Overflow,我能找到的最接近这个问题的答案只有 2 个不包含另一个列表的列表。

【问题讨论】:

  • 在没有 loat 理解的情况下,您在解决这个问题上取得了任何进展吗?如果是这样,请显示它以及任何相关的错误。
  • @BenG-TW,该副本不考虑列表的大小不等

标签: python list-comprehension


【解决方案1】:

您可以将嵌套列表推导与 zipitertools.zip_longest 一起使用:

import itertools
list1 = [[7,8], []]
list2 = [[3,4,2],[6,9]]

>>> [[x+y for x,y in itertools.zip_longest(i1,i2,fillvalue=0)] for i1,i2 in zip(list1,list2)]
[[10, 12, 2], [6, 9]]

list1 = [[], []]
list2 = [[3,4,2],[6,9]]

>>>[[x+y for x,y in itertools.zip_longest(i1,i2,fillvalue=0)] for i1,i2 in zip(list1,list2)]
[[3, 4, 2], [6, 9]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2012-05-09
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 2022-06-12
    • 2020-12-19
    • 1970-01-01
    相关资源
    最近更新 更多