返回迭代器、for循环中的屈服和从可迭代中的屈服之间有什么区别?

问题描述 投票:0回答:1

考虑以下三个函数。

def return_iter(iterable):
    return iter(iterable)

def for_loop_yield(iterable):
    for item in iterable:
        yield item

def yield_from_iter(iterable):
    yield from iterable

它们在循环时都产生相同的结果。

>>> prog_langs = ['python', 'java', 'c++']
>>> for lang in return_iter(prog_langs):
...     print(lang)
python
java
c++
>>> for lang in for_loop_yield(prog_langs):
...     print(lang)
python
java
c++
>>> for lang in yield_from_iter(prog_langs):
...     print(lang)
python
java
c++

它们的区别是什么?

python python-3.x iterator generator yield
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.