Question
有如下一个字典,内嵌多维列表:
dic = {
'hit_410000':[[1,11,21],[2,12,22]],
'pku_410000':[[100,200,300],[200,400,600]],
'hit_420000':[[3,13,23],[4,14,24]],
'hit_430000':[[5,15,25],[6,16,26]],
}
请把所有以 'hit' 开头的key所对应的list按顺序求和,示例结果:{ 'hit':[[9, 39, 69], [12, 42, 72]] }
Answer
#!/usr/bin/python2.7
dic = {
'hit_410000':[[1,11,21],[2,12,22]],
'pku_410000':[[100,200,300],[200,400,600]],
'hit_420000':[[3,13,23],[4,14,24]],
'hit_430000':[[5,15,25],[6,16,26]],
}
# 首先获取 'hit' 开头的list
new_dic = {}
for k,lst in dic.items():
prefix,code = k.split('_')
if prefix not in new_dic:
new_dic[prefix] = [lst]
else:
new_dic[prefix].append(lst)
hit_lst = new_dic['hit'] if 'hit' in new_dic else None
# 把多维list转化成字典形式:
# {0: [[1, 11, 21], [3, 13, 23], [5, 15, 25]], 1: [[2, 12, 22], [4, 14, 24], [6, 16, 26]]}
tmp = {}
for i in range(len(hit_lst)):
lst = hit_lst[i]
for j in range(len(lst)):
if j not in tmp:
tmp[j] = []
tmp[j].append(lst[j])
# 使用reduce结合lambda表达式求和
length = 3
final_res = []
for _,lst in tmp.items():
sums = reduce(lambda x,y:[x[i]+y[i] for i in range(length)], lst, [0]*length)
final_res.append(sums)
print final_res
# 结果:[[9, 39, 69], [12, 42, 72]]