我有一个json格式列表,每个列表中都有一些字典,它看起来像以下内容:
[{"id":13, "name":"Albert", "venue":{"id":123, "town":"Birmingham"}, "month":"February"},
{"id":17, "name":"Alfred", "venue":{"id":456, "town":"London"}, "month":"February"},
{"id":20, "name":"David", "venue":{"id":14, "town":"Southampton"}, "month":"June"},
{"id":17, "name":"Mary", "venue":{"id":56, "town":"London"}, "month":"December"}]
列表中的条目数最多为100。对于以伦敦为城镇的条目,我计划为每个条目显示“名称”,一次给出一个结果。其余的对我毫无用处。我是python的初学者,所以我对如何有效地解决此问题提出了建议。最初,我认为最好删除所有没有伦敦的条目,然后再逐个进行审核。
我还想知道是否不进行过滤而是循环遍历整个json并选择具有该镇作为伦敦的条目的名称是否更快。
答案 0 :(得分:3)
您可以使用filter
:
data = [{"id":13, "name":"Albert", "venue":{"id":123, "town":"Birmingham"}, "month":"February"},
{"id":17, "name":"Alfred", "venue":{"id":456, "town":"London"}, "month":"February"},
{"id":20, "name":"David", "venue":{"id":14, "town":"Southampton"}, "month":"June"},
{"id":17, "name":"Mary", "venue":{"id":56, "town":"London"}, "month":"December"}]
london_dicts = filter(lambda d: d['venue']['town'] == 'London', data)
for d in london_dicts:
print(d)
这是有效率的,因为:
filter
返回一个迭代器(在Python 3中),这意味着结果将按要求一一加载到内存中。答案 1 :(得分:0)
一种方法是使用列表理解:
>>> data = [{"id":13, "name":"Albert", "venue":{"id":123, "town":"Birmingham"}, "month":"February"},
{"id":17, "name":"Alfred", "venue":{"id":456, "town":"London"}, "month":"February"},
{"id":20, "name":"David", "venue":{"id":14, "town":"Southampton"}, "month":"June"},
{"id":17, "name":"Mary", "venue":{"id":56, "town":"London"}, "month":"December"}]
>>> [d for d in data if d['venue']['town'] == 'London']
[{'id': 17,
'name': 'Alfred',
'venue': {'id': 456, 'town': 'London'},
'month': 'February'},
{'id': 17,
'name': 'Mary',
'venue': {'id': 56, 'town': 'London'},
'month': 'December'}]