简体   繁体   English

用命名元组填充的列表的最大值

[英]max value of a list filled with named tuples

I create a list filled with named tuples: 我创建一个填充有命名元组的列表:

from collections import namedtuple
Point = namedtuple('Point', 'x y')
a = Point(5,4)
b = Point(8,3)
tab = [a,b]

print tab
>>[Point(x=5, y=4), Point(x=8, y=3)]

I would like to have the max of the x values in the list 'tab' 我想在“标签”列表中获得x值的最大值

max(tab.x)
>> 8

Try like this, 这样尝试

>>> max(tab, key=lambda k: k.x)
Point(x=8, y=3)
>>> max(tab, key=lambda k: k.x).x
8

The optional key argument specifies a one-argument ordering function like that used for list.sort(). 可选的key参数指定一个单参数排序函数,例如用于list.sort()的函数。 The key argument, if supplied, must be in keyword form (for example, max(a,b,c,key=func)). 如果提供了key参数,则必须采用关键字形式(例如max(a,b,c,key = func))。

https://docs.python.org/2/library/functions.html#max https://docs.python.org/2/library/functions.html#max

You may simple do it as : 您可以简单地这样做:

print max([i.x for i in tab])

However it may not be the best approach to do the same. 但是,这可能不是最好的方法。

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

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