将列表或元组展平,然后在Python中找到最大值?

2024-04-25 07:36:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到包含其他列表或元组的列表或元组的最大值。我的第一个想法是将它展平,然后使用max()函数从整个列表中找到最大值,但我很难做到这一点。 有什么建议吗?你知道吗

例如,您有一个元组:(1,2,3,(1,2)),预期的输出是3

另一个例子是列表[1,(2,3),[4,5]],输出应该是5

这是使用展平函数并调用它的两个步骤:

def flatten(t):
output = []
for item in t:
    if type(item) != type([]) or type(()):
        output.append(item)
    else:
        output.extend(flatten(item))
return output

def max_val(t):
    flatten(t)
    return max(output)

Tags: 函数in列表foroutputreturndeftype
3条回答

你可以使用更多的工具来扁平化你所拥有的东西。你知道吗

import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
res = list(more_itertools.flatten(lst))

然后您只需要使用max()函数。你知道吗

您可以使用^{}^{}定义泛型函数来展平输入:

from itertools import chain
from collections import Iterable

x = (1, 2, 3, (1, 2))
y = [1, (2, 3), [4, 5]]

def flatten(x):
    return chain.from_iterable([i] if not isinstance(i, Iterable) else i for i in x)

res = max(flatten(x)) # 3

res = max(flatten(y)) # 5

您可以使用自定义函数来展平iterable,并使用标准的maxmin函数:

from collections.abc import Iterable

x = (1, 2, 3, (1, 2))

def my_flatten(iterable):
    for value in iterable:
        if isinstance(value, Iterable):
            yield from my_flatten(value)
        else:
            yield value

print('min = ', min(my_flatten(x)))
print('max = ', max(my_flatten(x)))

输出:

min =  1
max =  3

相关问题 更多 >