python 获取列表中最大项目的 Pythonic 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1874194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pythonic way to get the largest item in a list
提问by Stephen Paulger
Is there a better way of doing this? I don't really need the list to be sorted, just scanning through to get the item with the greatest specified attribute. I care most about readability but sorting a whole list to get one item seems a bit wasteful.
有没有更好的方法来做到这一点?我真的不需要对列表进行排序,只需扫描即可获得具有最大指定属性的项目。我最关心可读性,但对整个列表进行排序以获得一个项目似乎有点浪费。
>>> import operator
>>>
>>> a_list = [('Tom', 23), ('Dick', 45), ('Harry', 33)]
>>> sorted(a_list, key=operator.itemgetter(1), reverse=True)[0]
('Dick', 45)
I could do it quite verbosely...
我可以很详细地做...
>>> age = 0
>>> oldest = None
>>> for person in a_list:
... if person[1] > age:
... age = person[1]
... oldest = person
...
>>> oldest
('Dick', 45)
回答by fengb
max(a_list, key=operator.itemgetter(1))
回答by tgray
You could use the max
function.
您可以使用该max
功能。
Help on built-in function max in module __builtin__:
max(...)
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item. With two or more arguments, return the largest argument.
关于 __builtin__ 模块中内置函数 max 的帮助:
最大限度(...)
max(iterable[, key=func]) -> 值
max(a, b, c, ...[, key=func]) -> 值
使用单个可迭代参数,返回其最大的项目。对于两个或更多参数,返回最大的参数。
max_item = max(a_list, key=operator.itemgetter(1))
回答by Richard Shepherd
The key can also be a lambda, for example:
键也可以是 lambda,例如:
people = [("Tom", 33), ("Dick", 55), ("Harry", 44)]
oldest = max(people, key=lambda p: p[1])
For some reason, using a lambda makes it feel more like "my code" is doing the work, compared with itemgetter
. I think this feels particularly nice when you have a collection of objects:
出于某种原因,与itemgetter
. 我认为当您拥有一组对象时,这感觉特别好:
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Tom", 33), Person("Dick", 55), Person("Harry", 44)]
oldest = max(people, key=lambda p: p.age)
回答by Emil Ivanov
回答by David Shaked
Some people mentioned the following solution:
有人提到了以下解决方案:
max(nameOfList, key=len)
However, this solution only returns the first sequential element of largest size. So, for example, in the case of list ["ABC","DCE"], only the first item of the list is returned.
但是,此解决方案仅返回最大尺寸的第一个顺序元素。因此,例如,在列表 ["ABC","DCE"] 的情况下,仅返回列表的第一项。
To remedy this, I found the following workaround using the filter function:
为了解决这个问题,我使用过滤器功能找到了以下解决方法:
filter((lambda x: len(x)==len(max(nameOfList, key=len))),nameOfList)