Python 列表列表

2024-09-30 22:14:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表列表,我应该找到第二个元素具有最大值的子列表。你知道吗

我实现它如下,但我要说它有点“次优”:-)

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

然后呢

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

有没有一种方法可以用更精确的形式来实现呢?你知道吗

非常感谢您的提示! 拜伊 法比奥


Tags: 方法in元素列表forreturnifvalue
3条回答

这里有另一个选择(虽然不是很有效):

查找第二个元素具有最大值的所有子列表:

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

查找其第二个元素具有最大值的第一个子列表:

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


为了提高效率,将其分成两条语句:

查找第二个元素具有最大值的所有子列表:

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

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

查找其第二个元素具有最大值的第一个子列表:

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

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

另一种使用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)

输出:

['county2', 20]

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

^{}接受可选的key参数;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]

相关问题 更多 >