• python可分组字典


    # -*- encoding: UTF-8 -*-
    from collections import defaultdict
    
    class News(object):
        def __init__(self, title, type):
            self.title =title
            self.type = type
    
        def __repr__(self):
            return "{'title':'%s', 'type':%s}"%(self.title, self.type)
    
    
    newses = [
          News(u"宏观研究", 1), 
          News(u"策略报告", 1), 
          News(u"行业研究", 2), 
          News(u"公司研究", 3), 
          News(u"海外资讯", 3), 
          News(u"其他", 1)
    ]
    #print newses 
    
    #{
    #   1: [{'title':宏观研究, 'type':1}, {'title':策略报告, 'type':1}, {'title':其他, 'type':1}], 
    #   2: [{'title':行业研究, 'type':2}], 
    #   3: [{'title':公司研究, 'type':3}, {'title':海外资讯, 'type':3}]
    #}
    
    #方法一
    d = {}
    for n in newses:
        if n.type not in d:
            d[n.type] = []
        d[n.type].append(n)
    #print d
    
    #方法二
    d = {}
    for n in newses:
        d.setdefault(n.type, []).append(n)
    #print d
    
    #方法三
    d = defaultdict(list)
    for n in newses:
        d[n.type].append(n)
    #print d
    
    #方法四
    d = defaultdict(list)
    map(lambda n:d[n.type].append(n),newses)
    #print d
    
    #方法五
    d = defaultdict(list)
    [d[n.type].append(n) for n in newses]
    #print d
    
    #输出
    for key in d:
        print key, d[key]
        
    print '=============='
    for key in d:
        for value in d[key]:
            print key, value
        print '=============='
  • 相关阅读:
    数据库_初学
    数据库—修改表的列
    做一个导航栏(bootstrap)
    几个比较常用的特效
    当、你想给一个目标挂上一个事件时
    图片轮播的几个小程序
    JS练习题 ( 下拉菜单;好友选中输入)
    Bootstrap 按钮和折叠插件
    Bootstrap 轮播插件
    Bootstrap 弹出框和警告框插件
  • 原文地址:https://www.cnblogs.com/linjiqin/p/4283648.html
Copyright © 2020-2023  润新知