我想知道类似于下面草图的代码在 Python 中是否合法并且可以安全使用:
# Example usage of a lambda which executes a statement and returns the changed operand
skip_first = lambda iterator: (next(iterator), iterator)[1]
使用这样的构造并期望 lambda 的返回值是从原始迭代器的第二个元素开始的迭代器(如果没有抛出异常)是否安全?
或者它对 f.i. 可能是合法的。 Cython 优化调用 next
出于某种原因(即,因为它丢弃了结果值,因为未定义元组中的执行顺序,并且它可以弄清楚我们以任何方式丢弃第一个值? )
- 使用示例:
f = iter([0, 1, 2, 3, 4])
print(list(skip_first(f)))
最佳答案
是的,表达式列表中的表达式保证从左到右计算。来自Section 6.15 of the language documentation :
expression_list ::= expression ("," expression)* [","] starred_list ::= starred_item ("," starred_item)* [","] starred_expression ::= expression | (starred_item ",")* [starred_item] starred_item ::= assignment_expression | "*" or_expr
Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
在您的特定示例中,无法优化对 next
的调用,因为它可能(并且确实)有副作用(即,它修改了迭代器的内部状态)。只有在没有可变值的语言中,您才能消除未使用返回值的函数调用。如果一个函数可以改变一个值,您必须假设它可以并允许调用发生。否则,您将更改所写代码的语义。
关于Python:生成元组的语句的执行顺序是否有保证?多语句 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67794210/