猿问

过滤带有嵌入字典的列表

我有一个 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 并选择将城镇作为伦敦的条目的名称是否会更快。


繁星coding
浏览 157回答 2
2回答

人到中年有点甜

您可以使用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)这是尽可能有效的,因为:循环是用 C 编写的(在 CPython 的情况下)filter 返回一个迭代器(在Python 3中),这意味着根据需要将结果一一加载到内存中

一只甜甜圈

一种方法是使用列表理解:>>> 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'}]
随时随地看视频慕课网APP

相关分类

Python
我要回答