Python merges duplicates in a single list and merges results

ive got a list in python that looks like

['Nickey, 20', 'John, 50', 'Nickey, 30']

I just want it to remove duplicates, however combine the numbers so that the result is

['Nickey, 50', 'John, 50']

I tried the following

A = {'a':1, 'b':2, 'c':3}
B = {'b':3, 'c':4, 'd':5}
c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
print c

but since you can see that the list is formatted differently, I pulled mine from the txt file ...

Is there a way to use get, set, union, but with my list formatting - and can I do this with a single list instead of merging 2

+4
source share
4 answers

One approach is to create a dictionary to store the total for the name:

from collections import defaultdict

people = ['Nickey, 20', 'John, 50', 'Nickey, 30']
people_map = defaultdict(int)
for person in people:
    name, number_str = person.split(', ')
    people_map[name] += int(number_str)

print ['{}, {}'.format(person, total) for person, total in people_map.iteritems()]
+1
source

We must use reducehere.

from collections import defaultdict
# below required for Python 3
# from functools import reduce

data = ['Nickey, 20', 'John, 50', 'Nickey, 30']

def accum(sums, p):
  sums[p[0]] += int(p[1])
  return sums

cum = reduce(accum, [s.split(', ') for s in data], defaultdict(int))
print(cum)

As an alternative, we can use collections.Counter:

from collections import Counter
import operator

cum = reduce(operator.iadd,
          (Counter({k: int(v)}) for k, v in (s.split(', ') for s in data)), Counter())
print(cum)
+1
a = [ 'Nickey, 20', 'John, 50', 'Nickey, 30' ]
d = dict()
t = list()

for i in a:
    t = i.split( ", " )
    d[t[0]] = d.get( t[0], 0 ) + int(t[1])

print( [ ", ".join([k,str(v)]) for k,v in d.items() ] )

['Nickey, 50', 'John, 50']

0

dict get():

data = ['Nickey, 20', 'John, 50', 'Nickey, 30']
names = {}
for value in data:
    k, v = value.split(', ')
    names[k] = names.get(k, 0) + int(v)

result = ['{}, {}'.format(k, v) for k, v in names.items()]
0

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


All Articles