蟒蛇。列表清单

时间:2016-11-19 09:00:20

标签: python list

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

我按照以下方式实施了它,但我会说它有点“次优”' : - )

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]

有一种方法可以用更巧合的形式来实现这一目标吗?

非常感谢您的任何提示! 再见 法比奥

3 个答案:

答案 0 :(得分:7)

max接受可选的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]

答案 1 :(得分:0)

这是另一种选择(虽然效率不高):

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

[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]

答案 2 :(得分: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