【问题标题】:Python, how to create a iterable with the same type as a random iterablePython,如何创建与随机迭代具有相同类型的迭代
【发布时间】:2019-01-13 14:46:33
【问题描述】:

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

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

【问题讨论】:

  • 如果输入是另一个可迭代的,例如产生值的函数怎么办?在这种情况下你会返回什么?

标签: python types iterable flatten


【解决方案1】:

这个应该做的:

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

【讨论】:

    【解决方案2】:
    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)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2012-03-04
      • 2015-04-24
      • 2019-06-26
      • 2015-02-10
      • 2012-03-04
      相关资源
      最近更新 更多