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

标签 python

我想在 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 一样。

关于python - 执行此操作的 pythonic 方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957826/

相关文章:

python - 将字符串添加到数据框两列中的重复字符串

python - 独立滚动矩阵的行

python - 如何防止 FIFO 队列有条件挂起

python - Python + Pandas 中的差异

python - Pygame - 矩形在我到达之前就消失了

python - 如何使用python将鼠标光标置于屏幕中央

python - 从 sql 字符串中提取表名、列等参数

python - Statsmodels 混合线性模型预测

修改环境的 Python 子进程/Popen

python - Python 采样模块