如果我向我的函数添加 "else",为什么会得到一个空列表?
Why do I get an empty list if I add an "else" to my function?
如果我执行这段代码,我会得到一个空列表:
#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]
为什么会这样,我对生成器有什么误解?
使用 yield
关键字,您实际上是在创建 "generator" 而不是函数。正如您在生成器中的 link, (PEP-380 https://www.python.org/dev/peps/pep-0380/) 中所见,语句 return value
在语义上等同于 raise StopIteration(value)
。关键是,如果你想做一个函数或一个生成器,不要混合使用 yield
和 return
关键字。
可能的修改:更改第一个 if
语句的结果,使其不使用 return
关键字,即使用 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]
为什么会这样,我对生成器有什么误解?
使用 yield
关键字,您实际上是在创建 "generator" 而不是函数。正如您在生成器中的 link, (PEP-380 https://www.python.org/dev/peps/pep-0380/) 中所见,语句 return value
在语义上等同于 raise StopIteration(value)
。关键是,如果你想做一个函数或一个生成器,不要混合使用 yield
和 return
关键字。
可能的修改:更改第一个 if
语句的结果,使其不使用 return
关键字,即使用 yield
并手动实现范围调用。