dic = {}
dic[3] = [1,2,3]
dic[1] = [4,5,6]
dic[6] = [7,8]
S = np.sum(dic.values, axis=0)
dic
是字典{3: [1, 2, 3], 1: [4, 5, 6], 6: [7, 8]}
。 S
也应该是字典,对吗?
print(S) # <built-in method values of dict object at 0x7f36df660b88>
print(type(S)) # <class 'builtin_function_or_method'>
是否可以将S
转换为字典,例如{3: 6, 1: 15, 6: 15}
?
答案 0 :(得分:2)
您的代码存在以下问题:
S = np.sum(dic.values, axis=0)
dic.values
是一个函数。你必须叫它!但是,您得到的结果不是您期望的:
np.sum(np.array(dic.values()), axis=0)
[4, 5, 6, 1, 2, 3, 7, 8]
这是因为axis=0
的意思是:求和我在数组中找到的所有内容。
转换为:
[4, 5, 6] + [1, 2, 3] + [7, 8] = [4, 5, 6, 1, 2, 3, 7, 8]
因此,最好的解决方案是使用列表理解:
{k: sum(v) for k, v in dic.items()}
输出:
{1: 15, 3: 6, 6: 15}
答案 1 :(得分:1)
Group.findAll({
include: ['members'],
where:{
id: {
$in: sequelize.literal(`(select distinct group_id from usergroup where user_id = ${user_id})`)
}
}
})
.then(results => {
console.log(results);
})
.catch(err => {
console.log('err', err);
});
然后输出为dic = {3: [1, 2, 3], 1: [4, 5, 6], 6: [7, 8]}
S = {k: sum(v) for k, v in dic.items()}
。
如果您使用Python 2.x,请使用S = {3: 6, 1: 15, 6: 15}
而不是dic.iteritems()
。
答案 2 :(得分:1)
您可以尝试以下方法:
dic = {3: [1, 2, 3], 1: [4, 5, 6], 6: [7, 8]}
c = {k: sum(dic[k]) for k in dic}
# c = {3: 6, 1: 15, 6: 15}
答案 3 :(得分:0)
for sub in the_list:
for key in sub:
sub[key] = int(sub[key])