gpt4 book ai didi

python - 如何在 python 2 中彻底迭代?

转载 作者:行者123 更新时间:2023-12-01 03:57:34 26 4
gpt4 key购买 nike

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

最佳答案

要递归地迭代某些内容,您当然需要一个递归函数。这是一个可以分解为 listtuplesetfrozenset字典的值。它返回一个平面生成器,您可以轻松地在单个 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=" ")

输出如下:

1 2 3 4 5 6 8 9 10 3 4 5 4 16 7 8 1 2 3 4 5 6 

See this code running on ideone.com

关于python - 如何在 python 2 中彻底迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37178397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com