pythonグループ化可能辞書
6347 ワード
# -*- 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 '=============='