Python:使用`yield from`时出现奇怪的行为 [英] Python: Weird behavior while using `yield from`
问题描述
在下面的代码中,我遇到了RecursionError: maximum recursion depth exceeded
.
In the following code, I have run into a RecursionError: maximum recursion depth exceeded
.
def unpack(given):
for i in given:
if hasattr(i, '__iter__'):
yield from unpack(i)
else:
yield i
some_list = ['a', ['b', 'c'], 'd']
unpacked = list(unpack(some_list))
如果我使用some_list = [1, [2, [3]]]
,这很好用,但是当我尝试使用字符串时,效果不佳.
This works fine if I use some_list = [1, [2, [3]]]
, but not when I try it with strings.
我怀疑我对python的了解不足.任何指导表示赞赏.
I suspect my lack of knowledge in python. Any guidance appreciated.
推荐答案
字符串是无限可迭代的.甚至一个字符的字符串也是可迭代的.
Strings are infinitely iterable. Even a one-character string is iterable.
因此,除非为字符串添加特殊处理,否则始终会出现堆栈溢出:
Therefore, you will always get a stack overflow unless you add special handling for strings:
def flatten(x):
try:
it = iter(x)
except TypeError:
yield x
return
if isinstance(x, (str, bytes)):
yield x
return
for elem in it:
yield from flatten(elem)
注意:使用hasattr(i, '__iter__')
不足以检查i
是否可迭代,因为还有其他方法可以满足迭代器协议. 仅一种可靠的方法来确定是否可迭代的对象是调用iter(obj)
.
Note: using hasattr(i, '__iter__')
is not sufficient to check if i
is iterable, because there are other ways to satisfy the iterator protocol. The only reliable way to determine whether an object is iterable is to call iter(obj)
.
这篇关于Python:使用`yield from`时出现奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!