我有一个列表列表,我应该找到第二个元素具有最大值的子列表。你知道吗
我实现它如下,但我要说它有点“次优”:-)
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]
有没有一种方法可以用更精确的形式来实现呢?你知道吗
非常感谢您的提示! 拜伊 法比奥
这里有另一个选择(虽然不是很有效):
查找第二个元素具有最大值的所有子列表:
[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
函数的简单方法:输出:
https://docs.python.org/3.5/library/functions.html#sorted
^{} 接受可选的
key
参数;max
比较key
函数的返回值以确定哪个更大。你知道吗相关问题 更多 >
编程相关推荐