【问题标题】:Python, How to return result in same type as the input [duplicate]Python,如何返回与输入相同类型的结果[重复]
【发布时间】:2019-05-29 02:36:14
【问题描述】:

我想创建一个函数来展平所有可能的可迭代的基因组合,并以与输入相同的类型返回结果。

到目前为止,我创建了以下函数。但它不像我想要的那样工作。例如:

flatten_iterable(([1, 2, 3], {4, 5, 6}, (7, 8, 9)))

给出以下结果:

(1, 2, 3, {4, 5, 6}, 7, 8, 9)

如您所见,该集合仍然存在

当输入是一个集合时,我得到以下错误:

TypeError: unhashable type: 'list'

def flatten_iterable(something):
    new_list = []
    x = type(something)
    if isinstance(something, (list, tuple)):
        for a in something:
            new_list.extend(flatten_list(a))
    else:
        new_list.append(a_list)
    new_list2 = x(new_list)
    return new_list2

有谁知道如何解决这个问题?

【问题讨论】:

  • 问题是当输入是一个集合时,您将一个集合附加到new_list,然后您尝试再次将该列表转换为一个集合,但这不起作用,因为它包含一个集是不可散列的。您应该立即归还该套装(即使用 else: return something)。
  • 展平应该多深?
  • 实际上,鉴于 Python 对“可迭代”的定义,您所要求的(我的意思是“返回与输入相同类型的结果”部分)是完全不可能的。

标签: python python-3.x function types


【解决方案1】:

试试这个

def flatten_iterable(input_):
    for item in input_:
        if hasattr(item,'__iter__') and not isinstance(item, (str, bytes)):
            yield from flatten_iterable(item)
        else:
            yield item

【讨论】:

  • 检查Iterable 可能会使输入过度扁平化,因为字符串、文件和许多其他对象都是可迭代的。
  • 没错,我想我也应该在答案中添加bytes
【解决方案2】:

isinstance(something, (list, tuple)) 对于集合显然是错误的,这就是为什么您要将整个集合添加到结果中。更好的方法是检查hasattr(something, '__iter__')(需要注意的是它也会“压平”字符串)。不过,我更喜欢@mehrdad-pedramfar 的回答

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 2022-01-03
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2013-04-22
    相关资源
    最近更新 更多