繁体   English   中英

如何在2d python列表中找到最大数量

[英]How to find maximum number in a 2d python list

我在python中有一个列表

my_list = [2,4,6,[5,10,3]]

如何找到最大数量(即程序应该将最大值返回10)?

谢谢

展平您的列表, 然后您可以使用max()内置函数:

l = [2,4,6,[5,10,3]]


def flatten(seq):
  for el in seq:
    if isinstance(el, list):
      yield from flatten(el)
    else:
      yield el

print(max(flatten(l))) # 10

可能更短/更好,但有一种方式:

my_list = [2,4,6,[5,10,3]]
print(max(max(x) if isinstance(x, list) else x for x in my_list))

为了找到最大值,迭代两次对我来说是额外的开销。 首先,为了展平列表然后再次找到最大值。 下面是创建递归函数以在单次迭代中返回嵌套列表的最大值的示例:

# The good thing is, you need not to worry about the level of depth
# of the nested list, you can use it on any level of nested list

def get_max(my_list):
    m = None
    for item in my_list:
        if isinstance(item, list):
            item = get_max(item)
        if not m or m < item:
            m = item
    return m

样品运行:

>>> my_list = [2,4,6,[5,10,3]]
>>> get_max(my_list)
10

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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