码迷,mamicode.com
首页 > 编程语言 > 详细

python可分组字典

时间:2015-02-10 15:00:40      阅读:159      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!