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

Python, how to create a iterable with the same type as a random iterable

我正在尝试创建一个函数来展平嵌套组合并以与输入具有相同类型的可迭代对象的形式传递它。例如:

>>> # 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]

这适用于接受可迭代对象作为参数的输入可迭代对象。我们得到输入可迭代对象的类型,然后用扁平化可迭代对象的生成器调用它。 (更恰当地说,我认为这只适用于 Collections)

这个应该做的:

def flatten_iterable(a_list):
    return type(a_list)([i for sub in a_list for i in sub])