python - 从列表中获取相关词典

标签 python list

我有两个不同词典的列表(ListA 和 ListB)。

listA 中的所有字典都有字段“id”和“external_id” listB 中的所有词典都有字段“num”和“external_num”

我需要获取所有字典对,其中 external_id 的值 = numexternal_num 的值 = id.

我可以使用这段代码实现:

for dictA in ListA:
    for dictB in ListB:
        if dictA["id"] == dictB["external_num"] and dictA["external_id"] == dictB["num"]:

但我看到了很多漂亮的 python 表达式,我想有可能得到更 pythonic 风格的结果,不是吗?

我喜欢:

res = [A, B for A, B in listA, listB if A['id'] == B['extnum'] and A['ext'] == B['num']]

最佳答案

你已经很接近了,但你并没有告诉 Python 你想如何连接两个列表来获得字典对 AB

如果你想比较ListA中的所有字典和ListB中的所有字典,你需要itertools.product :

from itertools import product

res = [A, B for A, B in product(ListA, ListB) if ...]

或者,如果您想要相同索引的对,请使用 zip :

res = [A, B for A, B in zip(ListA, ListB) if ...]

如果您不需要一次构建整个列表,请注意您可以使用 itertools.ifilter选择你想要的对:

from itertools import ifilter, product

for A, B in ifilter(lambda (A, B): ..., 
                    product(ListA, ListB)):
    # do whatever you want with A and B

(如果您使用 zip 执行此操作,请改用 itertools.izip 以最大化性能)。


关于 Python 3.x 的注释:

  • zipfilter no longer return lists ,因此 itertools.izipitertools.ifilter 不再存在(就像 range 推出了 xrange)和您只需要 itertools 中的 product;和
  • lambda (A, B):no longer valid syntax ;您将需要编写过滤函数以采用单个元组参数 lambda t: 和例如将 A 替换为 t[0]

关于python - 从列表中获取相关词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24577426/

相关文章:

java - 一个二维数组空间中的 2 个或多个元素 JAVA

python - PyLint/PyLint3 无法识别文档字符串

以内存高效方式聚合对象属性的 Pythonic 方式?

python - Spotipy client_credential_manager 未提供 token

python - 在 Python 中从 .pfx 证书获取公钥

java - 在 Java 中迭代少量固定数量的值的最佳方法是什么?

list - 标准 Haskell 函数::(a -> Maybe a) -> a -> [a]

python - 如何根据 if 语句的结果缩短附加到不同列表的时间

python - 如何从 Numpy 数组中删除最后 n 行?

python - 如何从多对多字段中获取所有数据?