简体   繁体   English

为多维数组的每个元素添加值

[英]add value to each element of a multidimensional array

I want to know how I can add a value to each element of a NXN multidimensional array.我想知道如何为 NXN 多维数组的每个元素添加一个值。 I tried [x+1 for x in multiArray], but this one yields only for a 1D array.我试过 [x+1 for x in multiArray],但这个只产生一维数组。

Maybe something like this:也许是这样的:

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

addingArray=[]
for i in range(3):
    for j in range(3):
        addingArray.append(multiArray[j]+1) #(adding 1 to each element here)  

But this seems to be wrong?但这似乎是错误的?

You're getting 1D array as result because you have addingArray as a simple list.结果是一维数组,因为您将addingArray作为简单列表。 So, you iterate over all the elements in your multiArray and add 1 to it and you're appending the result to a list.因此,您遍历multiArray中的所有元素并向其添加 1,然后将结果附加到列表中。


For efficiency reasons, it is advisable to use NumPy for arrays.出于效率原因,建议对 arrays 使用 NumPy。 Then, you can simply use broadcasting to add value to each element of the array.然后,您可以简单地使用广播为数组的每个元素添加值。 Below is an illustration:下面是一个插图:

# input array
In [180]: multiArray = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 

# add 1 to each value of the array
In [181]: multiArray + 1  
Out[181]: 
array([[ 2,  3,  4],
       [ 5,  6,  7],
       [ 8,  9, 10]])

If you indeed want a plain python list as the result for some reasons, you can simply cast it to one:如果出于某些原因您确实想要一个普通的 python 列表作为结果,您可以简单地将其转换为一个:

In [182]: (multiArray + 1).tolist()  
Out[182]: [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Indice-iteration索引迭代

You need to have a inner list to get the inner results, and access the good value with multiArray[i][j] , also don't use constant 3 take the habit to use object length您需要有一个内部列表才能获得内部结果,并使用multiArray[i][j]访问好的值,也不要使用常量3习惯使用 object 长度

addingArray=[]
for i in range(len(multiArray)):
    innerArray = []
    for j in range(len(multiArray[i])):
        innerArray.append(multiArray[i][j]+1)
    addingArray.append(innerArray)  

print(addingArray) # [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

Value iteration价值迭代

You can also iterate over the arra directly to simplify and don't both with indices您还可以直接迭代 arra 以简化并且不要同时使用索引

addingArray=[]
for inner in multiArray:
    innerArray = []
    for value in inner:
        innerArray.append(value+1)
    addingArray.append(innerArray)  

List comprehension列表理解

And shorten it with list comprehension syntax并用列表理解语法缩短它

multiArray = [[v+1 for v in inner] for inner in multiArray]
print(multiArray) # [[2, 3, 4], [5, 6, 7], [8, 9, 10]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM