• 多维列表按序求和问题


    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]]
  • 相关阅读:
    VS 2012 + NDK + ADT 开发(Cocos2d-x 3.1开发)PART 2
    VS 2012 + NDK + ADT 开发(Cocos2d-x 3.1开发)PART 1
    WebView读取SD卡上的HTML
    安卓隐藏控件
    OMNET++安装
    产品质量的核心——概念的完整性
    关于异常
    基类与子类之间的引用转换
    成绩划分 处理异常
    《大道至简 第七、八章》读后感
  • 原文地址:https://www.cnblogs.com/standby/p/9353692.html
Copyright © 2020-2023  润新知