S
The most efficient and simple using standard Python (outside specialized libraries like NumPy) is to use the builtins sum and minYou have several possibilities:Next to generating expression:M = [[1, 2, 3], [0, 3, 4], [3, 7, 8]]
minimo = min(min(row for row in M))
maximo = max(max(row for row in M))
Using map (functional approach):M = [[1, 2, 3], [0, 3, 4], [3, 7, 8]]
minimo = min(map(min, M))
maximo = max(map(max, M))
Using itertool.chain.from_iterable to flatten the list:import itertools
M = [[1, 2, 3], [0, 3, 4], [3, 7, 8]]
minimo = min(itertools.chain.from_iterable(M))
maximo = max(itertools.chain.from_iterable(M))
No use min/max you can use exactly the same idea you pose in your code for a list but using an extra for iterar on the sublists:M = [[1, 2, 3], [0, 3, 4], [3, 7, 8]]
minimo = float("inf")
maximo = float("-inf")
for row in M:
for item in row:
if item < minimo:
minimo = item
if item > maximo:
maximo = item
If we evaluate the execution time for a list of 30,000 rows, for example, in my case I get:# min/max and generator4.02 ms ± 115 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) # min/max e itertools.chain.from_iterable6.39 ms ± 42.7 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) # min/max and map11.4 ms ± 278 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) # Cycles for annuity, variables and conditional7.58 ms ± 187 μs per loop (mean ± std. dev. of 7 runs, 100 loops each) In this case min/max and the generating expression is the most efficient. map In this case it seems to fail conceitably. ...