gpt4 book ai didi

Python 迭代

转载 作者:行者123 更新时间:2023-11-30 23:53:23 27 4
gpt4 key购买 nike

有人知道为什么这段代码无法顺利运行吗?它似乎不喜欢使用yield关键字进行迭代:我正在尝试从任何级别的列表或字典中挖掘所有数字(对列表特别感兴趣)。在第二次迭代中,它找到 [2,3] 但无法依次打印 2 和 3...想象一下我可以有很多级别的列表。

def digIn( x ):
try:
if isDict(x) or isList(x):
print "X:", x
for each in x:
print "each:", each
if isDict(each) or isList(each):
digIn(each)
else:
yield each
else:
yield x
except Exception,ex:
print ex

print "STARTING OVER"
for i in digIn( [1,[2,3]] ):
print i

最佳答案

您应该“重新生成”生成器以递归地迭代所有列表元素。

if isDict(each) or isList(each):
for elem in digIn(each):
yield elem
else:
yield each

关于Python 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5748094/

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