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 '=============='

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值