while (command := input("> ")) != "quit":
print("You entered:", command)
b)简化列表理解
例如:
stuff = [(lambda y: [y,x/y])(f(x)) for x in range(5)]
可以变成:
stuff = [[y := f(x), x/y] for x in range(5)]
语法和语义
In any context where arbitrary Python expressions can be used, a named expression can appear. This is of the form name := expr where expr is any valid Python expression, and name is an identifier.
The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value
Naming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts.
PEP 572包含许多细节,尤其是第一个问题。我将尽量简明地总结/引用政治公众人物最重要的部分:
基本原理
允许在理解(如列表理解)和lambda函数中使用这种形式的赋值,而传统的赋值是被禁止的。这也可以促进交互调试,而无需进行代码重构。
推荐的用例示例
a)获取条件值
例如(在Python 3中):
可以变成:
b)简化列表理解
例如:
可以变成:
语法和语义
与常规赋值语句的区别
除了是表达式而不是语句之外,PEP中还提到了一些差异:表达式赋值从右向左,逗号周围的优先级不同,并且不支持:
下面是我最喜欢的几个例子,其中赋值表达式可以使代码更简洁、更易于阅读:
if
语句之前:
之后:
无限
while
语句之前:
之后:
有other good examples in the PEP。
现在3.8已经正式发布了,还有一些例子和基本原理。
来源:LicensedProfessional's reddit comment
相关问题 更多 >
编程相关推荐