Skip to main content
 首页 » 编程设计

python之执行此操作的 pythonic 方法是什么

2025年05月04日14dudu

我想在 while 中写一些速记表达式(比如 c),但它在 python 中行不通。

while token=TokenBuffer.peek() and token != sentinel 
    doSomeThing() 

请您参考如下方法:

您不能在 Python 中执行此操作。赋值是 Python 中的语句,而不是表达式。

那么,您可以做什么呢?最pythonic可能是使用iter功能:

for token in iter(TokenBuffer.peek, sentinel): 

这方面的文档对新手来说有点困惑:

… If the second argument, sentinel, is given, then object must be a callable object. The iterator created in this case will call object with no arguments for each call to its __next__() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

如果您已经了解迭代器和 for 循环的幕后工作原理,那就太好了,但如果您不了解,下面的示例可能会更有帮助:

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp: 
    for line in iter(fp.readline, ''): 
        process_line(line) 

这样就更清楚了:for line in iter(fp.readline, ''): 一遍又一遍地调用 fp.readline() 直到它得到一个''。就像您想一遍又一遍地调用 TokenBuffer.peek() 直到获得 sentinel 一样。