Skip to content

请编写一个生成器,将任意多维的列表转换为一维列表 #101

@Sogrey

Description

@Sogrey
nestedList = [4,[1,2,[3,5,6]],[4,3,[1,2,[4,5]],2],[1,2,4,5,7]]
print(nestedList)

def enumList(nestedList):
    try:
        for subList in nestedList:
            for element in enumList(subList):
                yield element
    except TypeError:
        yield nestedList   # 迭代单个值

for num in enumList(nestedList):
    print(num, end=' ')
print(list(enumList(nestedList)))

递归生成器的编写方法与递归函数类似,只是需要处理元素值的时候需要使用yield关键字

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions