[英]What is the most pythonic way to iterate over a list until a condition is met?
[英]What is the most pythonic way of looping in a list until a particular value?
我最近才了解到iter函數的第二個參數,該參數可用於循環直到滿足特定條件。
with open(file, 'r') as f:
for chunk in iter(lambda _ : f.read(8192), ''):
print(chunk)
但是,由於iter僅接受函數,因此我只能通過將列表轉換為生成器函數並將其轉換為iter來為列表編寫類似的代碼。 因此,我想知道是否還有更Python化的方式來做到這一點。 請注意,我已經看到了Padraic的回答 ,我僅指的是平等條件。
另一種方法是使用發電機
def file_iterator(filehandle, chunksize=8192, sentinel=''):
while True:
result = f.read(chunksize)
if result == sentinel:
return
yield result
with open(file, 'r') as f:
for chunk in file_iterator(file):
print(chunk)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.