【发布时间】:2014-09-23 17:03:33
【问题描述】:
我有一个这样结构的字典列表:
[
{'state': '1', 'city': 'a'},
{'state': '1', 'city': 'b'},
{'state': '2', 'city': 'c'},
{'state': '2', 'city': 'd'},
{'state': '3', 'city': 'e'}
]
我想这样打包:
[
{'state': '1', 'cities': ['a', 'b']},
{'state': '2', 'cities': ['c', 'd']},
{'state': '3', 'cities': ['e']}
]
我有一个可行但非常慢的两步方法(我的列表长度超过 10000 项,而且我的字典很复杂):
def pack(iterable):
# step 1: lists -> super slow ! contains duplicates
listed = [{'state': i['state'],
'cities': [c['city'] for c in iterable if c['state']==i['state']]}
for i in iterable]
# step 2: remove duplicates
packed = [l for n, l in enumerate(listed) if not l in listed[n+1:]]
return packed
有什么优化建议吗?
Ps:欢迎对帖子标题提出建议。
2014/09/26 编辑:我刚刚发现 pandas 非标准库在这种情况下很有帮助。
下面我的自我回答中有更多示例。
【问题讨论】:
-
这不是一个“线程”,它是一个问题。为了改进工作代码,您可能需要codereview.stackexchange.com
-
不知道 codereview.stackexchange.com。感谢您的建议!
标签: python list dictionary pandas group-by