Python字典问题。如何对相似字符串分组?
for i in names:
dict[i] = {'firstname': name[i]['firstname'],
'lastname': name[i]['lastname']}
print dict[0]['firstname'] # John
print dict[0]['lastname'] # Doe
# group similar lastnames, along with their firstnames
# ...
return render_to_response('index.html', dict)
我想把那些姓氏相似的名字分在一起。
比如,输出应该是这样的:
<html>
<body>
<h1> Doe </h1>
<p> John, Jason, Peter </p>
<h1> Avery </h1>
<p> Kelly, Brittany </p>
</body>
</html>
'h1' 标签应该放姓氏,而 'p' 标签则放名字。
我该怎么做呢?
2 个回答
1
你也可以在对名字进行排序之后使用groupby。你可以在这里查看相关内容:http://docs.python.org/library/itertools.html#itertools.groupby
6
你是说像这样:
import collections
data = [
{'firstname': 'John', 'lastname': 'Smith'},
{'firstname': 'Samantha', 'lastname': 'Smith'},
{'firstname': 'shawn', 'lastname': 'Spencer'},
]
new_data = collections.defaultdict(list)
for d in data:
new_data[d['lastname']].append(d['firstname'])
print new_data
输出结果:
defaultdict(<type 'list'>, {'Smith': ['John', 'Samantha'], 'Spencer': ['shawn']})
在你的模板里这样做:
{% for lastname, firstname in data.items %}
<h1> {{ lastname }} </h1>
<p> {{ firstname|join:", " }} </p>
{% endfor %}
输出:
<h1> Smith </h1>
<p> John, Samantha </p>
<h1> Spencer </h1>
<p> shawn </p>