大嵌套列表的 max()

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

我正在尝试获取所有对中第一个元素的最大值。 从 Python 的角度来说,我在做:

max([max(x) for x in list])[0]

这实际上是 returns 正确的数字,如果列表少于 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]

效率更高。