[英]max() of big nested lists
在處理成對的長列表的最大值時遇到了一個很奇怪的問題,例如
[
[(0, 1), (1, 1), (2, 1), (3, 4), (4, 1), (5, 1), (6, 1),...,(141,3)],
...,
[(12, 1), (36, 1), (91, 1), (92, 1), (110, 1),..., (180, 1)]
]
我正在嘗試獲取所有對中第一個元素的最大值。 Pythonly,我在做:
max([max(x) for x in list])[0]
如果列表短於281個列表,則實際上返回正確的數字。 實際上,只要列表超過280,我就會收到此消息
ValueError: max() arg is an empty sequence
所以,很長的清單
max([max(x) for x in list[0:280]])[0]
沒關系
max([max(x) for x in list[0:281]])[0]
休息。
我在這里做錯什么了嗎?
列表列表中的索引為280,您的列表中有一個空列表。最多切片[:280]
會將其排除在外,並且[:281]
中將其包括在內。
這可以用較短的樣本輕松重現:
>>> lsts = [
... [(0, 1), (1, 1)],
... [(2, 1), (3, 4)],
... [(4, 1), (5, 1)],
... [], # empty at index 3
... ]
>>> max(max(x) for x in lsts)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <genexpr>
ValueError: max() arg is an empty sequence
>>> max(max(x) for x in lsts[:3]) # include everything before index 3
(5, 1)
通過將列表鏈接在一起,可以完全避免該問題,這里使用chain.from_iterable()
:
from itertools import chain
max(chain.from_iterable(list_of_lists))[0]
這會將所有嵌套列表視為一個長列表,介於兩者之間的某個空列表根本不會影響該新序列。
為什么不只是這個呢?
max([max([t[0] for t in sl if t]) for sl in l if sl])
您可以從頭開始提取第一項。 空列表和元組將被忽略。
編輯
max([max([t for t in sl if t]) for sl in l if sl])[0]
更有效率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.