我正在尝试查找包含其他列表或元组的列表或元组的最大值。我的第一个想法是将其展平,然后使用max()函数从整个列表中找到最大值,但我很难做到这一点。有什么建议吗?
例如,您有一个元组:(1,2,3,(1,2)),并且预期输出为3
另一个例子是列表[1,(2,3),4,5],输出应该是5
这是使用flatten函数并调用它的take two:
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)发布于 2018-07-15 20:07:45
您可以创建自定义函数来扁平化您的迭代器,并使用标准的max或min函数:
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发布于 2018-07-15 22:18:05
您可以使用chain.from_iterable和collections.Iterable定义一个泛型函数来展平您的输入
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发布于 2018-07-15 20:02:17
您可以使用more_itertools包来展平已有的内容。
import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
res = list(more_itertools.flatten(lst))然后,您只需要使用max()函数。
https://stackoverflow.com/questions/51348133
复制相似问题