【问题标题】:Add integers of two lists of lists together将两个列表列表的整数相加
【发布时间】:2021-02-28 20:51:52
【问题描述】:

我正在尝试编写一个函数,该函数接受两个数字列表并返回一个列表,其中两个给定列表中的每个相应数字加在一起。不使用任何第三方库(例如不使用 pandas)。

它应该像这样工作:

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> add(matrix1, matrix2)
[[3, -3], [-3, 3]]

我当前的代码:

list_3 = []


# Add function

def add(*args):
    for arg in args:
        for i in range(0, len(args)):
                list_3.append(arg[i - 1] + arg[i - 1] + arg[i - 1])
                print(f"Result: {list_3}")

我的代码不起作用。帮助将不胜感激。

【问题讨论】:

  • 欢迎来到 StackOverflow! “我的代码不起作用”不是一个非常有用的问题描述。您可能想要编辑问题并解释您的代码实际在做什么以及为什么会出错。包括您遇到的任何错误。
  • @Mark 如果您阅读了它所说的全部内容:不使用任何第三方库。

标签: python python-3.x list add nested-lists


【解决方案1】:

这很容易通过使用 zip 的几个嵌套推导来完成:

>>> matrix1 = [[1, -2], [-3, 4]]
>>> matrix2 = [[2, -1], [0, -1]]
>>> [[a + b for a, b in zip(x, y)] for x, y in zip(matrix1, matrix2)]
[[3, -3], [-3, 3]]

或者可能使用mapsum 来构建内部列表:

>>> [list(map(sum, zip(x, y))) for x, y in zip(matrix1, matrix2)]
[[3, -3], [-3, 3]]

【讨论】:

  • 不错的一个。我想出了[list(map(operator.add, v1, v2)) for v1, v2 in zip(matrix1, matrix2)]
  • 是的,我想在您发表评论的同时使用 map 内部列表:D 尽管我通常更喜欢列表理解的可读性而不是 list(map(...
  • 感谢它的工作!你只需要让它成为一个功能,否则它会很棒。
  • 感谢@Matthias 的第二部分
【解决方案2】:

您可以遍历参数,然后遍历每个参数的项目。

def add(*args):
    list_tmp = []
    for arg in args:
        for item in arg:
            list_tmp.append(item)
    return list_tmp

我还建议您将项目存储在局部变量 (list_tmp) 中并返回:您可以避免使用全局变量。

【讨论】:

  • 感谢您的回答,但我现在想添加每个元素。它写在问题中。
猜你喜欢
  • 1970-01-01
  • 2018-04-25
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 2015-07-29
  • 1970-01-01
相关资源
最近更新 更多