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万的列表).您对更有效的方法有什么建议吗?
还有一个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)
| 归档时间: |
|
| 查看次数: |
116 次 |
| 最近记录: |