如果在函数中添加“ else”,为什么会得到一个空列表?

时间:2018-09-24 04:15:48

标签: python python-3.x if-statement generator yield

如果执行这段代码,我将得到一个空列表:

#quick.py
def test(key): 
    print('the input key is:',key)   
    if key==1: 
        return range(1,13)
    else:
        month = ['15','30']
        for i in range(1,53):
            if i==4: 
                yield '2904'
            else:
                str_i = str(i)
                if i<10:
                    str_i= '0'+str_i 
                yield month[0] + str_i if i % 2 else month[1] + str_i

my_list = list(test(1))
print('the list is :' ,my_list)


pc@pc-host:~/Git/PasivicSerious$ python3 quick.py
    the input key is: 1
    the list is : []

但没有“ else”,我得到了所需的列表:

def test(key): 
    print('the input key is:',key)   
    if key==1: 
        return range(1,13)
    # else:
    #     month = ['15','30']
    #     for i in range(1,53):
    #         if i==4: 
    #             yield '2904'
    #         else:
    #             str_i = str(i)
    #             if i<10:
    #                 str_i= '0'+str_i 
    #             yield month[0] + str_i if i % 2 else month[1] + str_i

my_list = list(test(1))
print('the list is :' ,my_list)


pc@pc-host:~/Git/PasivicSerious$ python3 quick.py
the input key is: 1
the list is : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

为什么会发生这种情况,我对发电机有什么误解?

1 个答案:

答案 0 :(得分:3)

使用yield关键字,实际上是在创建“生成器”而不是函数。如您在此链接中看到的,(PEP-380 https://www.python.org/dev/peps/pep-0380/)在生成器中,语句return value在语义上等效于raise StopIteration(value)。关键是,如果要创建函数或生成器,请不要混用yieldreturn关键字。

可能的修改:更改第一个if语句的结果,使其不使用return关键字,即使用yield并手动实现范围调用。