Get max length of multi-dimension tuple
Asked Answered
V

3

11

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 )
Veliz answered 7/4, 2012 at 21:11 Comment(1)
The extra , in the tuples are actually important. A number in parenthesis is just a number, if you add the , it becomes a 1-item tuple. (I know it's not relevant for you anymore. Just in case somebody else needs it)Stamey
T
15
tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
max(map(len,tup))

result:

4
Tref answered 7/4, 2012 at 21:17 Comment(3)
thanks! ps today I looked for the first time at functional programming, this solution was inspired by itTref
@JoelCornett no problem, I rejected the edit with the "custom" reasonTref
Link to the map function if you're not familiar with it: docs.python.org/2/library/functions.html#mapAtc
F
8

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.

Frannie answered 7/4, 2012 at 21:14 Comment(1)
This was merely for question purpose. My actual variable names are like: tScreens for a tuple of screen and so one. Thanks.Veliz
D
8

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'.

Druce answered 7/4, 2012 at 22:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.