Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

python - How can I do assignments in a list comprehension?

I want to use the assignment operator in a list comprehension. How can I do that?

The following code is invalid syntax. I mean to set lst[0] to an empty string '' if it matches pattern:

[ lst[0] = '' for pattern in start_pattern if lst[0] == pattern ]

Thanks!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Python 3.8 will introduce Assignment Expressions.

It is a new symbol: := that allows assignment in (among other things) comprehensions. This new operator is also known as the walrus operator.

It will introduce a lot of potential savings w.r.t. computation/memory, as can be seen from the following snippet of the above linked PEP (formatting adapted for SO):

Syntax and semantics

In most contexts 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 other than an unparenthesized tuple, 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:

  1. Handle a matched regex

    if (match := pattern.search(data)) is not None:
        # Do something with match
    
  2. A loop that can't be trivially rewritten using 2-arg iter()

    while chunk := file.read(8192):
        process(chunk)
    
  3. Reuse a value that's expensive to compute

    [y := f(x), y**2, y**3]
    
  4. Share a subexpression between a comprehension filter clause and its output

    filtered_data = [y for x in data if (y := f(x)) is not None]
    

This is already available in the recently releases alpha version (not recommended for production systems!). You can find the release schedule for Python 3.8 here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...