为了账号安全,请及时绑定邮箱和手机立即绑定

过滤带有嵌入字典的列表

过滤带有嵌入字典的列表

繁星coding 2021-11-02 20:30:07
我有一个 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 并选择将城镇作为伦敦的条目的名称是否会更快。
查看完整描述

2 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

您可以使用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中),这意味着根据需要将结果一一加载到内存中


查看完整回答
反对 回复 2021-11-02
?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

一种方法是使用列表理解:


>>> 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'}]


查看完整回答
反对 回复 2021-11-02
  • 2 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信