将两个列表合并到一个字典中,并对第二个列表的元素求和

Had*_*das 3 python dictionary numpy

如果我有两个列表(长度相同):

ls1 = ['a','b','c','a','d','c']
ls2 = [1,2,3,5,1,2]
Run Code Online (Sandbox Code Playgroud)

我想得到以下字典(如果它是相同的键,则对值进行求和):

d = {'a':6,'b':2,'c':5,'d':1}
Run Code Online (Sandbox Code Playgroud)

我做了以下事情:

ls1 = np.array(ls1)
ls2 = np.array(ls2)
uniqe_vals = list(set(ls1))
d = {}
for u in uniqe_vals:
    ind = np.where(ls1 == u)[0]
    d[u] = sum(ls2[ind])
Run Code Online (Sandbox Code Playgroud)

它适用于小数据,但整个数据花费的时间太长(我有一个大小约为500万的列表).您对更有效的方法有什么建议吗?

Jue*_*gen 6

还有一个defaultdict,但不同和简单:

from collections import defaultdict

d = defaultdict(int)
for n, v in zip(ls1, ls2):
   d[n] += v
Run Code Online (Sandbox Code Playgroud)

或者,如建议的那样:

from collections import defaultdict
from itertools   import izip

d = defaultdict(int)
for n, v in izip(ls1, ls2):
   d[n] += v
Run Code Online (Sandbox Code Playgroud)