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

时间:2018-08-06 15:30:19

标签: 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具有与输入相同的类型。

2 个答案:

答案 0 :(得分:1)

{
    "timestamp": "2018-08-09T13:29:34.536+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "status 405 reading InputFormatClient#checkFormat(String); content:\n{\"timestamp\":\"2018-08-09T13:29:34.504+0000\",\"status\":405,\"error\":\"Method Not Allowed\",\"message\":\"Request method 'POST' not supported\",\"path\":\"/\"}",
    "path": "/"
}

这适用于接受可迭代项作为参数的输入可迭代项。我们得到可迭代输入的类型,然后使用展平可迭代的生成器进行调用。 (更正确地说,我认为这仅适用于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] s)

答案 1 :(得分:1)

这应该做:

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