合并一个列表中的重复元素并将结果合并

2024-04-20 04:00:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python编写了一个列表

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

我只是想让它删除重复,但是,合并数字,这样的结果是

^{pr2}$

我试过以下方法

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

但是你可以看到列表的格式不同,我从一个txt文件中提取了我的。。。在

有没有一种方法可以使用get、set、union,但是要格式化一个列表-我可以用一个列表来代替合并2吗


Tags: 文件方法intxt列表forget格式
3条回答
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']

我们应该在这里使用^{}。在

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)

或者,我们可以使用^{}

^{pr2}$

一种方法是创建一个字典来存储每个名称的总计数:

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()]

相关问题 更多 >