说实话,我真的不知道如何正确地解释我想要的东西,所以我最好把它展示给大家看。
a = [[5, 4, 5, 4], [4, 5, 6, 8]]
b = [[1, 2, 4, 5], [5, 6, 6, 2]]
我想把它们合并到一个名为c的二维数组中,所以它应该像这样。
c = [[6, 6, 9, 9], [9, 11, 12, 10]]
我看了一下,但是sum和zip函数没有给我想要的结果。先谢谢你的帮助
一个简单的列表理解和 zip
就可以了,使用。
c = [[x + y for x, y in zip(s1, s2)] for s1, s2 in zip(a, b)]
结果:
#print(c)
[[6, 6, 9, 9], [9, 11, 12, 10]]
其实我可以用两个 压缩 函数,一个在另一个里面。
c = []
for x, y in zip(a, b):
array = []
for e1, e2 in zip(x, y):
array.append(e1+e2)
c.append(array)
print(c)
输出将是:
[[6, 6, 9, 9], [9, 11, 12, 10]]
你要找的基本上是矩阵加法:
import numpy as np
a = np.array([[5, 4, 5, 4], [4, 5, 6, 8]])
b = np.array([[1, 2, 4, 5], [5, 6, 6, 2]])
c = a + b
其中 "array "是numpy的向量和矩阵对象, 所以当你返回 "c "的时候, 你应该看到的是:
>>> c
array ([[6, 6, 9, 9],
[9, 11, 12, 10]])
由于你需要在一个新的数组中得到结果,我正在创建一个新的矩阵C作为A的副本,这样我就可以很容易地将B添加到A中。
c = a
for i in range(0,len(a)):
for j in range(0,len(a[0]):
c[i][j] = a[i][j] + b[i][j]
print(c)
你可以使用for循环来合并两个数组。
c = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
你可以使用嵌套循环来解决这个问题。
a = [[5, 4, 5, 4], [4, 5, 6, 8]]
b = [[1, 2, 4, 5], [5, 6, 6, 2]]
c=[]
l=len(a)
for i in range(l):
temp=[]
l2=len(a[i])
for j in range(l2):
p=a[i][j]+b[i][j]
temp.append(p)
c.append(temp)
print(c)
你可以使用一个循环来解决这个问题。
从buildins导入len
def insaneSum(x,y).A=[[5,4,5,4],[4,5,6,8]]B=[[1,2,4,5],[5,6,2]]。
newTable = x #creates a copie of your first array
i = 0
j = 0
while i < len(x):
while j < len(x[i]):
newTable[i][j] = x[i][j] + y[i][j] #replaces value of copie for the sum
j = j+1
i = i+1
return newTable
a = [[5, 4, 5, 4], [4, 5, 6, 8]]b = [[1, 2, 4, 5], [5, 6, 6, 2]] 。
c = insaneSum(a,b)print(c)