【问题标题】:How to find if all elements of a list are present in a list of dictionaries?如何查找列表的所有元素是否都存在于字典列表中?
【发布时间】:2021-11-06 14:09:17
【问题描述】:

我正在尝试用 Python 开发一个小脚本,但我从未使用过这种语言。

我的结构是这样的:

dict = [
    { "id" : 1,
      "people" : [ { "name" : "Sarah",
                     "surename" : "something"
                   },
                   { "name" : "Luke",
                    "surename" : "something"
                   },
                   { "name" : "Chris",
                   "surename" : "something"
                   }
                 ]
    },
    { "id" : 2,
      "people" : [ { "name" : "Jhon",
                     "surename" : "something"
                   },
                   { "name" : "Luke",
                    "surename" : "something"
                   },
                   { "name" : "Ronald",
                   "surename" : "something"
                   }
                 ]
    }
]

我还有另一个值列表,例如name_list = ["Sarah", "Luke"]

我需要找到结构的所有 ID,以便 name_list 中的所有名称都出现在字典列表 people 中。

我尝试过类似的方法,但这不起作用。

for person in dict:
   if all(name_list in p["name"] for p in person["people"]):
      # Do something with person["id"]

找到包含 所有 name_list 名称的字典列表的所有 ID 对我来说很重要。

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:
    ids = [item['id'] for item in d if all(name in [person['name'] for person in item['people']] for name in name_list)]
    print(ids)
    >>> [1]
    

    【讨论】:

      【解决方案2】:

      首先,dict 是一个内置函数,隐藏它可能会在以后为您破坏某些东西(例如,isinstance(obj, dict) 将不起作用)。

      假设您的输入存储在data 变量中:

      result = [
          d["id"] 
          for d in data 
          if not set(name_list) - {p['name'] for p in d['people']}
      ]
      

      这里的{p['name'] for p in d['people']}set comprehension。结果将是 people 结构的一组唯一名称,例如 {Sarah, Luke, Ronald}

      然后我们使用集差来查找name_list:set(name_list) - {Sarah, Luke, Ronald} == set()中哪些名字是不是的。

      如果 name_list 中的所有名称都在 people 结构中,则差异将等于一个空集。

      所以我们的目标是找到这种差异为空集的结构。

      set 算术将比使用in 运算符和列表快得多。

      In [1]: %timeit [item['id'] for item in d if all(name in [person['name'] for person in item['people']] for name in name_list)]
      1.43 µs ± 17.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      
      In [2]: %timeit [d["id"] for d in data if not set(name_list) - {p['name'] for p in d['people']}]
      869 ns ± 2.64 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
      

      【讨论】:

        猜你喜欢
        • 2017-08-09
        • 1970-01-01
        • 1970-01-01
        • 2015-10-03
        • 2019-12-22
        • 2021-11-15
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多