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

Is it possible to access current object while doing list/dict comprehension in Python?

Trying to think of a one-liner to achieve the following ( summing all the values of a key) :

>>> data = [('a',1),('b',3),('a',4),('c',9),('b',1),('d',3)]
>>> res = {}
>>> for tup in data:
...     res[tup[0]] = res.setdefault(tup[0],0) + tup[1]
... 
>>> res
{'a': 5, 'c': 9, 'b': 4, 'd': 3}

One-liner version without using any imports like itertools,collections etc.

 { tup[0] : SELF_REFERENCE.setdefault(tup[0],0) + tup[1]  for tup in data }

Is it possible in Python to use a reference to the object currently being comprehended ? If not, is there any way to achieve this in a one-liner without using any imports i.e. using basic list/dict comprehension and inbuilt functions.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

No, there is not. A dict comprehension produces a new item for each iteration, and your code needs to produce fewer items (consolidating values).

There is no way to access keys produced in an earlier iteration, not without using (ugly, unpythonic) side-effect tricks. The dict object that is going to be produced by the comprehension doesn't exist yet, so there is no way to produce a self-reference either.

Just stick to your for loop, it is far more readable.

The alternative would be to use sorting and grouping, a O(NlogN) algorithm vs. the simple O(N) of your straight loop:

from itertools import groupby
from operator import itemgetter

res = {key: sum(t[1] for t in group) 
       for key, group in groupby(sorted(data, key=itemgetter(0)), key=itemgetter(0))}

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

...