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

How to find maximum number in a 2d python list

我在 python 中有一个列表

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

我怎样才能找到最大数量(即程序应该 return 最大值为 10)?

谢谢

可能是 shorter/better 但一种方式是:

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

展平您的列表,然后然后您可以使用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

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

# 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