首页 > 编程语言 > 详细

python可分组字典

时间:2015-02-10 14:57:55      阅读:256      评论:0      收藏:0      [点我收藏+]
# -*- 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 ==============

 

python可分组字典

原文:http://www.cnblogs.com/linjiqin/p/4283648.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!