【问题标题】:how to get sum of 2 lists index by index in python?如何在python中按索引获取2个列表的总和?
【发布时间】:2021-01-23 14:50:50
【问题描述】:

例如,我有两个列表 a 和 b,其中有两个或多个列表(取决于我的输入) 我希望输出是 a[0] 和 b[0] 和 ...

的总和
n = int(input())
for i in range(n):
    x = list(map(int, input().split()))
    a.append(x)

for i in range(n):
    x2 = list(map(int, input().split()))
    b.append(x2)

现在例如 n = 2,之后我们将有 4 个输入 喜欢:

these will be appended to a
1 2 3
4 5 6
and these two will be appended to b
2 3 4
5 6 7

现在我希望我的输出是

3 5 7 
9 11 13 
as you can see a[0] + b[0]
and a[1] + b[1]

但我希望我的代码输出这样,即使我给我的 n 输入一个大于 2 的数字 例如,如果我给我的 n 输入 3,我将在 a 和 b 中有 3 个索引,它们都是列表,我希望输出与最后一个例子一样工作,

example 
for n = 3
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[3, 2, 1], [4, 5, 6], [9, 8, 7]]

【问题讨论】:

  • 你能添加给定示例的预期输出吗?

标签: python arrays python-3.x string list


【解决方案1】:

我想你正在寻找这个:

n = int(input())
a = []
b = []
for i in range(n):
    x = input().split()
    a.append(x)

for i in range(n):
    x2 = input().split()
    b.append(x2)

tabA = []
tabB = []

for l in range(len(a)):
    tabA.append([int(i) for i in a[l][0]])
    tabB.append([int(i) for i in b[l][0]])

print(tabA)
print(tabB)

print([[i+j for i, j in zip(x, y) ] for x,y in zip(tabA, tabB)])

【讨论】:

    【解决方案2】:
    [[i+j for i, j in zip(x, y) ] for x,y in zip(a, b)]
    

    【讨论】:

    • 请添加一些文字来解释您的答案。纯代码的答案不如包含解释的答案有用。
    【解决方案3】:

    试试这个:

    [[p[0]+p[1] for p in (zip(k[0],k[1]))] for k in list(zip(a,b))]
    

    对于

    a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    b = [[3, 2, 1], [4, 5, 6], [9, 8, 7]]
    

    它会给出:

    [[4, 4, 4], [8, 10, 12], [16, 16, 16]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多