f = (3, 4, 5, {3: 4}, [16, 7, 8])
g = (1, 2, [3, 4, [5, 6], {7: 8}], 9, 10, {11: f}, {12: [1, 2, {3, 4}, [5, 6]]})
我试图以g
递归迭代。
如何在python中递归迭代每个元素,它适用于任何嵌套级别的列表?
我尝试使用hasattr
,__iter__
但不适用于未知级别的嵌套。
f=(3,4,5,{3:4},[6,7,8])
g = (1, 2, [3, 4, [5, 6], {7: 8}], 9, 10, {11: (3, 4, 5, {3: 4}, [16, 7, 8])}, {12: [1, 2, set([3, 4]), [5, 6]]})
print g
for each in g:
print each
try:
if hasattr(each,"__iter__"):
for ind in each:
print ind
if hasattr(ind,"__iter__"):
for ind1 in ind:
print ind1
答案 0 :(得分:2)
要递归迭代某些东西,你当然需要一个递归函数。这是一个可以下载到list
,tuple
,set
,frozenset
和值的{{{ 1}}秒。它返回一个平面生成器,您可以在其中轻松迭代单个dictionary
循环:
for
以下是您将如何使用该功能:
def recursive_iterator(iterable):
for item in iterable:
# directly iterable types:
if type(item) in (list, tuple, set, frozenset):
for child_item in recursive_iterator(item):
yield child_item
# other iterable types where we do not want to iterate over the item directly:
elif type(item) in (dict,):
for child_item in recursive_iterator(item.values()):
yield child_item
# not iterable types which we want to return as they are:
else:
yield item
输出将是:
f = (3, 4, 5, {3: 4}, [16, 7, 8])
g = (1, 2, [3, 4, [5, 6], {7: 8}], 9, 10, {11: f}, {12: [1, 2, {3, 4}, [5, 6]]})
for x in recursive_iterator(g):
print(x, end=" ")