[英]Python. List of Lists
我有一個列表列表,我應該找到第二個元素具有最大值的子列表。
我實現如下,但我會說它有點'次優':-)
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]
有一種方法可以用更復雜的形式實現這一目標嗎?
非常感謝您的任何提示! 再見法比奧
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]
這是另一種選擇(雖然效率不高):
找到第二個元素具有最大值的所有子列表:
[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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.