Python,如何创建与随机可迭代相同类型的可迭代

标签 python types iterable flatten

我正在尝试创建一个函数,该函数可以展平嵌套组合并将其传递到与输入具有相同类型的迭代中。例如:

>>> # tuple with list, tuple and set
>>> flatten_iterable([[1,2,3],(1,2,3),{1,2,3}])
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> # set with tuples
>>> flatten_iterable({(1,2,3),(3,4,5),(5,6,7,8)})
{1, 2, 3, 4, 5, 6, 7, 8}
>>> # tuple with list, set, tuple
>>> flatten_iterable(([1,2,3],{3,4,5},(5,6,7,8)))
(1, 2, 3, 3, 4, 5, 5, 6, 7, 8)


到目前为止,我有以下代码:

def flatten_iterable(a_list):
    new_list = []
    import collections
    for i in a_list:
        if isinstance(i, collections.Iterable):
            new_list.extend(flatten_iterable(i))
        else:
            new_list.append(i)
    return new_list

但我只是不知道如何使 new_list 与输入具有相同的类型。

最佳答案

def _flatten_helper(iterable):
    for item in iterable:
        if isinstance(item, Iterable):
            yield from _flatten_helper(item)
        else:
            yield item

def flatten_iterable(iterable):
    return type(iterable)(_flatten_helper(iterable))

flatten_iterable([[1,2,3],(1,2,3),{1,2,3}])
# [1, 2, 3, 1, 2, 3, 1, 2, 3]

这适用于接受迭代作为参数的输入迭代。我们获取输入可迭代的类型,然后使用扁平可迭代的生成器调用它。 (更准确地说,我认为这只适用于Collection)

关于Python,如何创建与随机可迭代相同类型的可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51711056/

相关文章:

C#封装: Get types from other project

python - 如何使用 python 将 else 语句作为 lambda 的一部分添加到 for 循环内的 if

python - 结合 Python 跟踪信息和日志记录

python - beautifulSoup中attrMap和attrs的区别

python - 无法在 python 列表中追加字典列表

types - typescript 中的 GUID/UUID 类型

python - 如何从 Python 列表中排序和删除重复项?

haskell - Haskell Num 类和我的类似表演的类之间存在歧义

python - python3中的可迭代类

java - Iterable 接口(interface)是否有任何关于多次使用的官方契约(Contract)?