【问题标题】:Why do I get an empty list if I add an "else" to my function?如果我在函数中添加“else”,为什么会得到一个空列表?
【发布时间】:2019-02-27 13:40:31
【问题描述】:

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

#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]

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      相关资源
      最近更新 更多