如何在Python的二维列表中找到最大值

7

我有一个Python列表,如下:

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

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

谢谢

3个回答

3

可能会更短、更好的方式:

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

如果您只想支持一层平铺,您可以使用 max(max(x) if isinstance(x, list) else x for x in a),这会比您的表达式更简单。 - Sven Marnach
哦,是的。将其编辑进去是否是适当的做法? - Bijay Gurung
1
谢谢。我在这里是新手,所以很多情况下不知道正确的礼仪。 - Bijay Gurung

3

将您的列表扁平化,然后您可以使用内置函数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

谢谢!:) @leaf - jasmine
1
个人而言,我更喜欢使用列表推导式来展开二维列表,就像这样[i for lst in l for i in lst] - CervEd

1

对我来说,两次迭代查找最大值似乎多余。首先,需要展平列表,然后再查找最大值。以下是创建递归函数的示例,以在单次迭代中返回嵌套列表的最大值:

# 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接