zoukankan      html  css  js  c++  java
  • 多维列表按序求和问题

    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]]
  • 相关阅读:
    经典isset,empty,is_null三个的用法与区别,最详细的讲解
    TP框架分页bootstrap冲突问题
    TP框架右下角运行时间
    TP6的跳转坑 和cmd报错 php版本和composer扩展坑
    TP5.1模板继承
    TP5.1模型关联
    Oracle语句
    ajaxform和ajaxgrid获取数据源、添加数据
    confirm和alert弹窗
    UEP-弹窗
  • 原文地址:https://www.cnblogs.com/standby/p/9353692.html
Copyright © 2011-2022 走看看