简体   繁体   English

在列表中循环直到特定值的最pythonic方式是什么?

[英]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.

相关问题 在条件满足之前迭代列表的最pythonic方法是什么? - What is the most pythonic way to iterate over a list until a condition is met? 列表边界-最Python的方式是什么? - List boundaries - what is the most Pythonic way? 最蟒蛇的方式不断地遍历列表直到满足条件? - Most pythonic way to continually iterate over a list until a condition is met? 从元组列表中选择特定元组的大多数Python方法 - Most Pythonic Way to Select Particular Tuple from List of Tuples 将列表中的值用作另一个列表的索引的最pythonic方法 - most pythonic way to use a value from a list as an index to another list 忽略带有括号的列表中的单词的最有效(pythonic)方法是什么? - What is the most efficient (pythonic) way to ignore words in a list that has parantheses? 重构此列表构建代码的最Pythonic方法是什么? - What's the most Pythonic way to refactor this list building code? 从 OrderedDict 列表中查找项目的最pythonic 方法是什么? - what would be the most pythonic way of finding items from a list of OrderedDict? 什么是逻辑上结合布尔列表的最“pythonic”方式? - What is the most 'pythonic' way to logically combine a list of booleans? 从列表中弹出随机元素的最pythonic方法是什么? - What is the most pythonic way to pop a random element from a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM