python-assignment-expression

Is it possible to add a where clause with list comprehension?

喜夏-厌秋 提交于 2019-12-09 07:48:25
问题 Consider the following list comprehension [ (x,f(x)) for x in iterable if f(x) ] This filters the iterable based a condition f and returns the pairs of x,f(x) . The problem with this approach is f(x) is calculated twice. It would be great if we could write like [ (x,fx) for x in iterable if fx where fx = f(x) ] or [ (x,fx) for x in iterable if fx with f(x) as fx ] But in python we have to write using nested comprehensions to avoid duplicate call to f(x) and it makes the comprehension look

Is it possible to add a where clause with list comprehension?

点点圈 提交于 2019-12-03 09:44:24
Consider the following list comprehension [ (x,f(x)) for x in iterable if f(x) ] This filters the iterable based a condition f and returns the pairs of x,f(x) . The problem with this approach is f(x) is calculated twice. It would be great if we could write like [ (x,fx) for x in iterable if fx where fx = f(x) ] or [ (x,fx) for x in iterable if fx with f(x) as fx ] But in python we have to write using nested comprehensions to avoid duplicate call to f(x) and it makes the comprehension look less clear [ (x,fx) for x,fx in ( (y,f(y) for y in iterable ) if fx ] Is there any other way to make it

“:=” syntax and assignment expressions: what and why?

浪尽此生 提交于 2019-11-27 01:01:07
问题 PEP 572 introduces assignment expressions (colloquially known as the Walrus Operator ), implemented for Python 3.8. This seems like a really substantial new feature since it will allow this form of assignment within comprehensions and lambda functions. What exactly are the syntax, semantics, and grammar specification of assignment expressions? Why is this new (and seemingly quite radical concept) being introduced, when a similar idea in PEP 379 on "Adding an assignment expression" was