首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >展平列表或元组,然后在Python中找到最大值?

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

Stack Overflow用户
提问于 2018-07-15 19:56:27
回答 3查看 268关注 0票数 1

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

例如,您有一个元组:(1,2,3,(1,2)),并且预期输出为3

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

这是使用flatten函数并调用它的take two:

代码语言:javascript
复制
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)
EN

回答 3

Stack Overflow用户

发布于 2018-07-15 20:07:45

您可以创建自定义函数来扁平化您的迭代器,并使用标准的max或min函数:

代码语言:javascript
复制
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)))

输出:

代码语言:javascript
复制
min =  1
max =  3
票数 1
EN

Stack Overflow用户

发布于 2018-07-15 22:18:05

您可以使用chain.from_iterable和collections.Iterable定义一个泛型函数来展平您的输入

代码语言:javascript
复制
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
票数 1
EN

Stack Overflow用户

发布于 2018-07-15 20:02:17

您可以使用more_itertools包来展平已有的内容。

代码语言:javascript
复制
import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
res = list(more_itertools.flatten(lst))

然后,您只需要使用max()函数。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51348133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档