下面的代碼遍歷1到5之間的數字,調用forEachInRangeThisNumberLoopThreeTimes
函數將其傳遞給一個數字。該函數接受一個數字並將其循環三次,將每次迭代附加到最後返回的numbers
列表中。如何使用yield而不是return
def forEachInRangeThisNumberLoopThreeTimes(number):
numbers = []
for each in range(number):
for i in range(3):
numbers.append(i)
return numbers
result = []
for number in range(1, 5):
print number, forEachInRangeThisNumberLoopThreeTimes(number)
它打印:
1 [0, 1, 2]
2 [0, 1, 2, 0, 1, 2]
3 [0, 1, 2, 0, 1, 2, 0, 1, 2]
4 [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
相反追加後的數字result
變量我想用yield
:
def forEachInRangeThisNumberLoopThreeTimes(number):
for each in range(number):
for i in range(3):
yield i
現在,當我執行:
for number in range(1, 5):
result = forEachInRangeThisNumberLoopThreeTimes(number)
的result
是不是我所期望:
1 <generator object forEachInRangeThisNumberLoopThreeTimes at 0x104ebfaf0>
2 <generator object forEachInRangeThisNumberLoopThreeTimes at 0x104ebfaf0>
3 <generator object forEachInRangeThisNumberLoopThreeTimes at 0x104ebfaf0>
4 <generator object forEachInRangeThisNumberLoopThreeTimes at 0x104ebfaf0>
哪裏錯誤?