多维列表按序求和问题

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

 

转载于:https://www.cnblogs.com/standby/p/9353692.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值