简体   繁体   English

蟒蛇。 列表清单

[英]Python. List of Lists

I have a list of lists and I should find the sublist whose second element has the max value. 我有一个列表列表,我应该找到第二个元素具有最大值的子列表。

I implemented it as follows, but I would say it's a bit 'suboptimal' :-) 我实现如下,但我会说它有点'次优':-)

def max_value(inputlist):
    return max([sublist[-1] for sublist in inputlist])

and then 接着

maxvalue = max_value(listofcounties)    
for result in listofcounties:
    if result[1] == maxvalue:
        return result[0]

There's a way to accomplish that in a more coincise form? 有一种方法可以用更复杂的形式实现这一目标吗?

Thank you very much for any hint! 非常感谢您的任何提示! Bye Fabio 再见法比奥

max accepts an optional key parameter; max接受可选的key参数; max compares the return value of the key function to determine which one is larger. max比较key函数的返回值以确定哪一个更大。

maxvalue = max(listofcounties, key=lambda x: x[-1])

>>> listofcounties = [['county1', 10], ['county2', 20], ['county3', 5]]
>>> max(listofcounties, key=lambda x: x[-1])  # by using `key`, max compares 10, 20, 5
['county2', 20]

Here is another option (though not a very efficient one): 这是另一种选择(虽然效率不高):

Find all the sub-lists whose second element has the maximum value: 找到第二个元素具有最大值的所有子列表:

[n for n in listofcounties if n[1] == max([k[1] for k in listofcounties])]

Find the first sub-list whose second element has the maximum value: 找到第二个元素具有最大值的第一个子列表:

[n for n in listofcounties if n[1] == max([k[1] for k in listofcounties])][0]


Split it into two statements in order to improve efficiency: 将其拆分为两个语句以提高效率:

Find all the sub-lists whose second element has the maximum value: 找到第二个元素具有最大值的所有子列表:

maxvalue = max([k[1] for k in listofcounties])

[n for n in listofcounties if n[1] == maxvalue]

Find the first sub-list whose second element has the maximum value: 找到第二个元素具有最大值的第一个子列表:

maxvalue = max([k[1] for k in listofcounties])

[n for n in listofcounties if n[1] == maxvalue][0]

Another simple approach using sorted function: 使用sorted函数的另一种简单方法

# the exemplary list was borrowed from @falsetru answer
listofcounties = [['county1', 10], ['county2', 20], ['county3', 5]]
max_sequence = sorted(listofcounties, key=lambda l: l[1], reverse=True)[0]

print(max_sequence)

The output: 输出:

['county2', 20]

https://docs.python.org/3.5/library/functions.html#sorted https://docs.python.org/3.5/library/functions.html#sorted

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

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