我做了以下代碼,但沒有得到預期的輸出。
a=[1, 2, 3, 4, 5, 5, 6, 7, 78, 8, 9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i n]
def hello():
s=chunks(a,10)
print(list(s))
hello()
#output [[1, 2, 3, 4, 5, 5, 6, 7, 78, 8], [9, 9, 0, 0, 8, 6, 5, 4, 3, 4]]
expected output-:
[1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
---------New line----
[9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
僅當我能夠在 for 回圈中回傳時才有可能出現預期結果,這是不可能的。我認為。
提前致謝。
uj5u.com熱心網友回復:
s您hello方法中的變數是一個生成器物件。您可以簡單地迭代生成器并繼續在新行中列印值。
嘗試這個:
a=[1, 2, 3, 4, 5, 5, 6, 7, 78, 8, 9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i n]
def hello():
s=chunks(a,10)
for l in s:
print(l)
hello()
輸出:
[1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
[9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
uj5u.com熱心網友回復:
使用next()方法一一獲取生成器的元素。
a=[1, 2, 3, 4, 5, 5, 6, 7, 78, 8, 9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i n]
def hello():
s=chunks(a,10)
# s is a generator object
# to print the chunk use next method
print(next(s))
print(next(s))
hello()
輸出
[1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
[9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
uj5u.com熱心網友回復:
如果我理解正確,您需要一個執行以下操作的函式塊:
a = [1, 2, 3, 4, 5, 5, 6, 7, 78, 8, 9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
print(chunks(a, 10)) # [1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
print(chunks(a, 10)) # [9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
其余的答案基于該假設。
TL; 博士
不能(不應該)用簡單的函式來完成,使用生成器函式 next
長說明
據我所知,您不能為此使用簡單的函式,主要是因為您無法在函式中保持狀態。
您可以使用以下技巧(后果自負:)):
from itertools import count
a = [1, 2, 3, 4, 5, 5, 6, 7, 78, 8, 9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
def chunks(lst, n, counter=count()):
"""Yield successive n-sized chunks from lst."""
i = next(counter) * n
return lst[i:i n]
print(chunks(a, 10))
print(chunks(a, 10))
輸出
[1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
[9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
請注意,這通常是不受歡迎的,因為counter函式的引數chunks是默認的可變引數。另一種選擇是使用閉包:
def chunks_maker():
counter = count()
def _chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
i = next(counter) * n
return lst[i:i n]
return _chunks
chunks = chunks_maker()
print(chunks(a, 10))
print(chunks(a, 10))
輸出 (來自閉包)
[1, 2, 3, 4, 5, 5, 6, 7, 78, 8]
[9, 9, 0, 0, 8, 6, 5, 4, 3, 4]
但是,Python 的禪宗指出:
There should be one-- and preferably only one --obvious way to do it.
and that way at least in my humble opinion is to use a generator function next.
Other resources on keeping state without classes in Python are:
- How to maintain state in Python without classes
- Can a Python function remember its previous outputs
- What is the Python equivalent of static variables inside a function?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/336405.html
上一篇:試圖讓串列停止并在一定數量的條目后顯示一條訊息,但回圈繼續進行?
下一篇:for回圈的迭代次數
