Is there a one line code to find maximal value in a matrix?

前端 未结 4 1397
囚心锁ツ
囚心锁ツ 2021-01-08 01:27

To find the maximal value in a matrix of numbers, we can code 5 lines to solve the problem:

ans = matrix[0][0]
for x in range(len(matrix)):
    for y in rang         


        
相关标签:
4条回答
  • 2021-01-08 02:00

    You can also flatten your array:

    from itertools import chain
    
    flatten = chain.from_iterable
    
    max(flatten(matrix))
    
    0 讨论(0)
  • 2021-01-08 02:03

    using numpy.amax:

    import numpy as np
    >>> my_array
    array([[1, 2, 3],
           [9, 8, 6]])
    >>> np.amax(my_array)
    9
    
    0 讨论(0)
  • 2021-01-08 02:11

    By matrix, I assume you mean a 2d-list.

    max([max(i) for i in matrix])
    
    0 讨论(0)
  • 2021-01-08 02:14

    You can use generator expression to find the maximum in your matrix. That way you can avoid building the full list of matrix elements in memory.

    maximum = max(max(row) for row in matrix)
    

    instead of list comprehension as given in a previous answer here

    maximum = max([max(row) for row in matrix])
    

    This is from PEP (the rationale section):

    ...many of the use cases do not need to have a full list created in memory. Instead, they only need to iterate over the elements one at a time.

    ...

    Generator expressions are especially useful with functions like sum(), min(), and max() that reduce an iterable input to a single value

    ...

    The utility of generator expressions is greatly enhanced when combined with reduction functions like sum(), min(), and max().

    Also, take a look at this SO post: Generator Expressions vs. List Comprehension.

    0 讨论(0)
提交回复
热议问题