How to add tuple y values ​​if x values ​​are the same?

start = [(1,2),(3,4),(1,3),(3,5)]

How to add values ​​of y tuples if x values ​​are equally efficient (I work with 700,000 tuples)?

end = [(1,5),(3,9)]

What am I trying:

I am trying to convert my list of tuples to a list of individual dictionaries. However, this does not seem to me the most effective method.

However, then I cannot figure out how to convert the list of tuples into a list of individual dictionaries.

I tried dict (start) and this:

a = []
for lv in length_view:
    a.append(dict(lv))

How can i do this?

And then I will try to use:

from collections import Counter
c = Counter()
for some_dictionary in some_list:
    c.update(some_dictionary)

[{key: value} for key, value in c.items()]
+4
source share
3 answers

A method that I can think of using collections.defaultdict-

>>> from collections import defaultdict
>>> dic = defaultdict(int)
>>> for a, b in start:
...     dic[a] += b
...
>>> list(dic.items())
[(1, 5), (3, 9)]

If you are using Python 2.x you do not need list(..)around dic.items()since it .items()returns a list in python 2.x

+2

defaultdict .

from collections import defaultdict
start = [(1,2),(3,4),(1,3),(3,5)]
d = defaultdict(list)
for x,y in start:
    d[x].append(y)

print [(i,sum(j)) for i,j in d.items()] 
+1

dict.setdefault , sum :

>>> start = [(1,2),(3,4),(1,3),(3,5)]
>>> d={}
>>> for i,j in start:
...   d.setdefault(i,[]).append(j)
... 

>>> [(i,sum(j)) for i,j in d.items()]
[(1, 5), (3, 9)]

Or as a more efficient way to use collections.defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for i,j in start:
...     d[i]+=j
... 
>>> d.items()
[(1, 5), (3, 9)]
+1
source

Source: https://habr.com/ru/post/1598647/


All Articles