请编写一个生成器,将任意多维的列表转换为一维列表
nestedList = [1, [2, 3, [4, 5]], [5, 3, [7, 1, [2, 0]], 7, [1, 7, 5, 3]]]
print(nestedList)
[1, [2, 3, [4, 5]], [5, 3, [7, 1, [2, 0]], 7, [1, 7, 5, 3]]]
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()
print(list(enumList(nestedList)))
1 2 3 4 5 5 3 7 1 2 0 7 1 7 5 3
[1, 2, 3, 4, 5, 5, 3, 7, 1, 2, 0, 7, 1, 7, 5, 3]
正文完