簡體   English   中英

如何在 python 中按索引獲取 2 個列表的總和?

[英]how to get sum of 2 lists index by index in python?

例如,我有兩個列表 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

現在我希望我的 output 成為

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

但是我希望我的代碼像這樣 output 即使我給 n 輸入一個大於 2 的數字,例如如果我給 n 輸入 3 我將在 a 和 b 中有 3 個索引,它們都是列表,我想要 output像最后一個例子一樣工作,

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

試試這個:

[[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]]
[[i+j for i, j in zip(x, y) ] for x,y in zip(a, b)]

我想你正在尋找這個:

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)])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM