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
429 views
in Technique[技术] by (71.8m points)

python - How to reuse an expression in a comprehension expression?

Imagine a theoretical snippet:

# just for this example: `bad_structure` contains a list of dicts with different keys
# for the same semantic
bad_structure = [{'path': '/dir/one'}, {'subdir': '/dir/two'}]

# i want to turn this into
# { '/dir/one': some_func('/dir/one'),
#   '/dir/two': some_func('/dir/two')}

result = {}
for e in bad_structure:
  # calculate a value which we will need more than once (here the key)
  p = next(k for k in ('path', 'subdir') if k in e)
  result[p] = some_func(p)

I want to turn this into a dict comprehension now and my first approach looks like this:

bad_structure = [{'path': '/dir/one'}, {'path': '/dir/two'}]
result = {next(k for k in ('path', 'subdir') if k in e): 
          some_func(next(k for k in ('path', 'subdir') if k in e))
          for e in bad_structure}

which contains the 'calculation' twice which ugly, error prone and slow. I would like to rewrite it to s.th. like

result = {p: some_func(p) 
          for p = next(k for k in ('path', 'subdir') if k in e)
          for e in bad_structure}

which is no valid Python code of course..

Is something like this possible in Python?

For clarification: I don't care about comprehension syntax but reusing a calculation without separate variable declaration (which is not possible in closed expressions)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yes! Python 3.8 introduces the "Assignment operator" :=, which allows you to define a variable within the local scope of a single expression (e.g. a comprehension). In your example, you would do this:

result = {(p := next(k for k in ('path', 'subdir') if k in e)): some_func(p) 
          for e in bad_structure}

Disclaimer: this will not work in any version of python before 3.8.


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

...