在屈服时连接

时间:2017-05-10 22:03:58

标签: python generator yield

如果在python函数中产生函数时如何连接两个项?

基本案例:

import itertools

def test():
    for number in range(0,10):
        yield number

list(test()) # [0...9]

如果我想同时提供number及其方格number**2

,该怎么办?
import itertools

def test():
    for number in range(0,10):
        yield itertools.chain.from_iterable([
            number,number*2
        ])

list(test()) 

# [0,0,1,1,2,4,3,9,...] pretended
# <itertools.chain at 0x135decfd0> ... what I got

但是从外部做itertools.chain.from_iterable([generator1, generator2])会得到预期的结果。

def first_list():
    for number in range(0,5):
        yield number

def second_list():
    for number in range(5,10):
        yield number

list(itertools.chain.from_iterable([first_list(), second_list()]))

2 个答案:

答案 0 :(得分:10)

一个简单的方法是:

def test():
    for number in range(0,10):
        yield number 
        yield number**2

答案 1 :(得分:10)

Python 3.3还引入了yield from(另请参阅PEP-380)语法,它允许您执行以下操作:

>>> def test():
...   for number in range(10):
...     yield from (number, number**2)
...
>>> list(test())
[0, 0, 1, 1, 2, 4, 3, 9, 4, 16, 5, 25, 6, 36, 7, 49, 8, 64, 9, 81]