我有一个Python列表,如下:
my_list = [2,4,6,[5,10,3]]
我该如何找到最大值(即程序应返回最大值10)?
谢谢
可能会更短、更好的方式:
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
[i for lst in l for i in lst]
。 - CervEd对我来说,两次迭代查找最大值似乎多余。首先,需要展平列表,然后再查找最大值。以下是创建递归函数的示例,以在单次迭代中返回嵌套列表的最大值:
# 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
max(max(x) if isinstance(x, list) else x for x in a)
,这会比您的表达式更简单。 - Sven Marnach