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.
Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list.
Insert operation is to insert one or more data elements into an array. Based on the requirement, a new element can be added at the beginning, end, or any given index of array. Here, we add a data element at the middle of the array using the python in-built insert() method.
We can access elements of an array using the index operator [] . All you need do in order to access a particular element is to call the array you created. Beside the array is the index [] operator, which will have the value of the particular element's index position from a given array.
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]])
>>>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With