In my python code, I have an array that has different size inside like this
arr = [
[1],
[2,3],
[4],
[5,6,7],
[8],
[9,10,11]
]
I want to multiply them by 10 so it will be like this
arr = [
[10],
[20,30],
[40],
[50,60,70],
[80],
[90,100,110]
]
I have tried arr = np.multiply(arr,10)
and arr = np.array(arr)*10
it seems that both are not working for different size of nested array because when I tried using same size nested array, they actually works just fine
CodePudding user response:
It is best to just use a nested loop :
arr = [
[1],
[2,3],
[4],
[5,6,7],
[8],
[9,10,11]
]
def matrix_multiply_all(matrix,nb):
return list(map(lambda arr : list(map(lambda el : el*nb,arr)),matrix))
print(matrix_multiply_all(arr,10))
CodePudding user response:
You can do with list comprehension as sahasrara62 mentioned if it is a list:
[[i*10 for i in x] for x in arr]
CodePudding user response:
You need not to use Numpy for this,
Here is the code:
for i in range(len(arr)):
for j in range(len(arr[I])):
arr[i][j] = arr[i][j]*10
print(arr)
Output:
[[10], [20, 30], [40], [50, 60, 70], [80], [90, 100, 110]]
Even though this give answer it is not pythonic. More Pythonic code:
arr = [[j * 10 for j in i] for i in arr]
print(arr)
Output:
[[10], [20, 30], [40], [50, 60, 70], [80], [90, 100, 110]]