【问题标题】:Iterating over a list that has a combination of nested lists of different sizes, with itertools [duplicate]使用 itertools 迭代具有不同大小的嵌套列表组合的列表 [重复]
【发布时间】:2020-08-30 01:23:24
【问题描述】:

假设我有以下列表。

strange_list = [3, 4, 5, [6, 7, 8, [9, 0, 9], 4, 34, 'hello'], [[[['wtf']]]]]

如何使用 itertools 模块中的某些功能获得以下列表。

chain_strange_list = [3, 4, 5, 6, 7, 8, 9, 0, 9, 4, 34, 'hello', 'wtf']

【问题讨论】:

标签: python iterator itertools


【解决方案1】:

我们可以创建一个简单的递归函数来处理这个问题,而不需要任何导入。

def unpack(obj):
    if not isinstance(obj, list):
        yield obj
    else:
        for item in obj:
            yield from unpack(item)

list(unpack(strange_list))
>> [3, 4, 5, 6, 7, 8, 9, 0, 9, 4, 34, 'hello', 'wtf']

请记住,这里的基本条件很简单,因为它检查迭代中的当前项是否为列表。对于更复杂的数据类型,您必须修改此条件以满足您的需要。

【讨论】:

    【解决方案2】:

    您正在寻找的是扁平化列表,您可以检查这些: how to extract nested lists? Flatten list of lists How to make a flat list out of list of lists?

    因此请关注其中一位并感谢@Chris Charley 的提示:

    from more_itertools import collapse
    strange_list = [3, 4, 5, [6, 7, 8, [9, 0, 9], 4, 34, 'hello'], [[[['wtf']]]]]
    
    list(collapse(strange_list))
    # [3, 4, 5, 6, 7, 8, 9, 0, 9, 4, 34, 'hello', 'wtf']
    
    

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多