Get larger number of items in a Python list array

Asked

Viewed 756 times

4

I have a Python array composed of arrays. But these arrays can have different sizes. For example:

matriz = [[1,2,3],[4,5,6,7],[1,2,3,4,5,6]]

What I want to know is if there is a medium (some python function) that gives me the size of the largest array of this matrix.

For example:

x = funcao(matriz)

that would return x to value 6 (array size at position 3 of the matrix).

3 answers

6

Use max:

matriz = [[1,2,3],[4,5,6,7],[1,2,3,4,5,6]]
len_maior = len(max(matriz, key=len)) # tamanho da maior sublista, 6

max(matriz, key=len) will return to higher sublist ([1,2,3,4,5,6]), based on its len (size), then we will actually 'measure it' and know its size (len([1,2,3,4,5,6])), which is 6 in this case

DEMONSTRATION

  • Very good! Python always surprising me

  • 1

    @Math, key can take with methods, even you can make them using lambda

  • Cool! + 1 max looks well designed!

  • (: Obagdo @Jjoao

6

You can iterate your matrix by creating a Generator and using a len() to pick up the size of each element, thus: gen = (len(x) for x in matriz) and then use the function max() to catch the biggest element of Generator.

Example:

matriz = [[1,2,3],[4,5,6,7],[1,2,3,4,5,6]]
gen = (len(x) for x in matriz)
print(type(gen))
print(max(gen))

Exit:

<class 'generator'>
6

See working on ideone

  • Wait - when I voted there was more text explaining what you do there - you don’t need the comprehension list, true, but the explanation was good.

  • @jsbueno Poisé, I used the list comprehension because I had imagined something more complex at first, but it is possible to use the direct max in the iteration Generator, you think it is better that I explain it in more detail?

  • @jsbueno edited to explain in step by step, what you found?

  • T[bequeaths the explanation.

5

Other version:

max(map(len,matriz))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.