簡體   English   中英

Python:使用`yield from`時出現奇怪的行為

[英]Python: Weird behavior while using `yield from`

在以下代碼中,我遇到了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]]] ,這很好用,但是當我嘗試使用字符串時卻不能。

我懷疑我對python的了解不足。 任何指導表示贊賞。

字符串是無限可迭代的。 甚至一個字符的字符串都是可迭代的。

因此,除非為字符串添加特殊處理,否則總是會產生堆棧溢出:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM