Most Efficient Method To Find Maximum Element And List Of Maximum Elements From A 2-d Array?
Suppose I have a list arr=[[1,2,3],[4,5,6],[7,8,9]] here maximum element is 9 and maximum elements from 1 d list is [3,6,9].
Solution 1:
Flatten the array with a nested comprehension for the max of all elements:
>>>max(x for row in arr for x in row)
9
Use a list comprehension for the max of each row:
>>>[max(row) for row in arr]
[3, 6, 9]
Note: The list comp is slightly faster than using map(max, arr)
. Consider using numpy
if you want better performance than pure Python loops.
Solution 2:
If using numpy
>>>import numpy as np
>>>array=np.random.rand(3,3)
>>>print(array)
>>>print(array.max(axis=1))
>>>[[ 0.76562624 0.45225107 0.74276688]
[ 0.84390255 0.03384166 0.40036534]
[ 0.00371805 0.47996941 0.15593055]]
>>>[ 0.765626240.843902550.47996941]
Alternatively using map and max
>>>arr=[[1,2,3],[4,5,6],[7,8,9]]
>>>print(list(map(max,arr)))
>>>[3,6,9]
To print maximum element
>>>print(max(map(max,arr)))
>>>9
Using numpy
>>>print(array.max())
Solution 3:
>>>arr=[[1,2,3],[4,5,6],[7,8,9]] >>>max_row = map(max, arr)>>>list(max_row)
[3, 6, 9]
>>>maxmax = max(max_row)>>>maxmax
9
>>>_
Post a Comment for "Most Efficient Method To Find Maximum Element And List Of Maximum Elements From A 2-d Array?"