简体   繁体   English

获取多维元组的最大长度

[英]Get max length of multi-dimension tuple

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.我总是可以使用 for 循环,遍历所有子元组并执行它。 But I want to ask if there's a predefined function for the same.但我想问一下是否有一个预定义的 function 相同。

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 )
tup=[ (3, ), (1, 3), (6, 8), (4, 6, 8, 9), (2, 4) ]
max(map(len,tup))

result:结果:

4

You shouldn't use max as a variable name, since this will shadow the built-in of the same name.您不应该使用max作为变量名,因为这会掩盖同名的内置变量。 This built-in max() can be used to compute the maximum of an iterable.这个内置的max()可用于计算可迭代对象的最大值。

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.) (请注意,我将您的列表tuple重命名为tuples ,因为tuple会隐藏同名的内置类型。)

Now you can apply max() to this list, or even better, to a generator expression constructed in a similar way.现在您可以将max()应用于此列表,或者甚至更好地应用于以类似方式构造的生成器表达式。

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'.翻译为“给我tup的最大元素的长度,“最大”由元素的长度定义”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM