Reputation: 131
I am a beginner in Python. I try to store the max value of two array in an another array. The length of array is known so I used c=[]*len(a)
a=[3,4,6,8]
b=[9,4,5,10]
c=[]*len(a)
for i in range(len(a)):
if (a[i]>b[i]):
c.append(a[i])
else:
c.append(b[i])
I got the following output, which is correct.
c=[9,4,6,10]
If I have arrays like
a=[[2,4],[6,8]]
b=[[1,7],[5,9]]
How should I proceed this to store the max value of each elements in an another array? Thank for your help in advance.
Upvotes: 8
Views: 723
Reputation: 22953
You can use zip()
to zip together each list and each sublist to compare them element-wise:
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. [...].
>>> def max_value(lst1, lst2):
for subl1, subl2 in zip(lst1, lst2):
for el1, el2 in zip(subl1, subl2):
yield max(el1, el2)
>>>
>>> a=[[2,4],[6,8]]
>>> b=[[1,7],[5,9]]
>>>
>>> list(max_value(a, b))
[2, 7, 6, 9]
If using NumPy, you can use numpy.maximum()
:
Element-wise maximum of array elements.
Compare two arrays and returns a new array containing the element-wise maxima. [...].
>>> import numpy as np
>>>
>>> a = np.array([[2,4],[6,8]])
>>> b = np.array([[1,7],[5,9]])
>>>
>>> np.maximum(a, b)
array([[2, 7],
[6, 9]])
>>>
Upvotes: 10
Reputation: 1
a=[[2,4],[6,8]]
b=[[1,7],[5,9]]
c=[]*len(a)
for i in range(len(a)): #loop through the elements
for each in zip(a[i],b[i]): #for each number in a & b, zipped forming (2,1),(4,7) ...
c.append(max(each)) #append max number of each zipped pair to c
print(c) #print c
Upvotes: 0
Reputation: 11
In single line solution you can use map and lambda. For Example in this case the solution can be
a=[[2,4],[6,8]]
b=[[1,7],[5,9]]
map(lambda x,y : map(lambda p,q : max(p,q),x,y),a,b)
[[2, 7], [6, 9]]
Since a and b both are array of arrays the first lambda input are arrays and then next map takes the maximum of the individual element.
Upvotes: 1
Reputation: 572
To handle multi-dimensional arrays you can use two variables i
and j
which represents your rows and columns.
a=[[2,4],[6,8]]
b=[[1,7],[5,9]]
c=[]*len(a)
for i in range(len(a)):
for j in range(len(a)):
if (a[i][j]>b[i][j]):
c.append(a[i][j])
else:
c.append(b[i][j])
print(c)
Output:
[2, 7, 6, 9]
I have assumed c
is a 1 dimensional array.
Upvotes: 0