繁体   English   中英

大嵌套列表的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)]
]

我正在尝试获取所有对中第一个元素的最大值。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM