As his matriz
is a list of lists (a list in which each element is another list), use reduce
this way you will only go through the first level (ie you will be comparing whether one list is larger than another). To compare the numbers, you can use the module itertools
:
from functools import reduce
from itertools import chain
matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]]
result = reduce(lambda x , y: x if x > y else y, chain.from_iterable(matriz))
print(result) # 89
chain.from_iterable
takes all the sub-lists and transforms them into a single eternity, in which each element will be one of the numbers. So you can compare them correctly with the lambda (note also that the parentheses around the labmda are redundant and can be removed).
You said in the comments what to use reduce
is not mandatory, only the lambda. Therefore, one could be made loop simple:
matriz = [[4, 2, 56], [7, 46, 10], [3, 89, 2]]
maior = lambda x , y: x if x > y else y
result = float('-inf')
for linha in matriz:
for numero in linha:
result = maior(result, numero)
print(result) # 89
The detail is that I start result
with "least infinite" (the least possible value), so in the first comparison the first element of the matrix will surely be greater than it. In the other iterations, he compares the result
with each element, and in the end we have the largest.
Note: if it was not mandatory to use the lambda, it would be simpler to use max
, along with chain.from_iterable
:
result = max(chain.from_iterable(matriz))
Is it mandatory to use a matrix? It can be a converted matrix?
– lmonferrari
Yes, it is mandatory to use matrix.
– Camilla Marques
But the use of
reduce
?– Isac
No, as long as you stay with the lambda function to find the lowest value in the list.
– Camilla Marques