Domanda

My tuple looks something like this(for a particular set of generated value)

tTrains = [ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]

Now, what I need to find is the length of longest tuple inside this tuple/list. I can always use a for loop, iterate over all the sub-tuples and do it. But I want to ask if there's a predefined function for the same.

Current Usage

This is what I am going to use as of now

max = 0
for i in range( len(tTrains) ):
  if iMax < len( i ):
    iMax = len( i )
È stato utile?

Soluzione

tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
max(map(len,tup))

result:

4

Altri suggerimenti

You shouldn't use max as a variable name, since this will shadow the built-in of the same name. This built-in max() can be used to compute the maximum of an iterable.

You currently have a list of tuples, but you want the maximum of the list of their lengths. To get this list, you can use a list comprehension:

[len(t) for t in tuples]

(Note that I renamed your list tuple to tuples, since tuple would shadow the built-in type of the same name.)

Now you can apply max() to this list, or even better, to a generator expression constructed in a similar way.

Another solution:

>>> tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
>>> len(max(tup, key=len))
4

which translates to 'give me the length of the largest element of tup, with "largest" defined by the length of the element'.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top