[英]What is the most pythonic way of looping in a list until a particular value?
I just recently learned about the iter function's second argument which can be used to loop until a certain condition is met. 我最近才了解到iter函数的第二个参数,该参数可用于循环直到满足特定条件。
with open(file, 'r') as f:
for chunk in iter(lambda _ : f.read(8192), ''):
print(chunk)
However, since iter accepts only functions, I could only code a similar thing for a list by converting it into a generator function and it to iter. 但是,由于iter仅接受函数,因此我只能通过将列表转换为生成器函数并将其转换为iter来为列表编写类似的代码。 Hence, I was wondering if there was a more pythonic way of doing this. 因此,我想知道是否还有更Python化的方式来做到这一点。 Kindly note I have already seen Padraic's answer and I am specifically referring to just an equality condition. 请注意,我已经看到了Padraic的回答 ,我仅指的是平等条件。
another approach is with a generator 另一种方法是使用发电机
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.