python - 基于python中键值的2个字典列表中的2元组列表

标签 python list-comprehension

我有两个字典列表 lxlylx 的元素包含感兴趣的 key key1ly 的元素包含 key2。我想创建一个二元组 (a,b) 列表,其中 a 是来自 lx 的字典,b 是来自 ly 这样 a['key1'] == b['key2']。有没有办法直接通过列表推导来做到这一点?

我失败的尝试是:

out = [(a,b) for a in lx for b in ly and a['key1'] == b['key2']]

但我收到“赋值前引用的局部变量 b”错误。

更新:

一个示例输入是:

lx = [{'key1': 'a', 'xyz': 1}, 
      {'key1': 'b', 'xyz': 2}, 
      {'key1': 'c', 'xyz': 3}]

ly = [{'key2': 'a', 'abc': '66'}, 
      {'key2': 'c', 'abc': '01'}]

输出:

out = [({'key1': 'a', 'xyz': 1}, {'key2': 'a', 'abc': '66'}), 
       ({'key1': 'c', 'xyz': 3}, {'key2': 'c', 'abc': '01'})]

最佳答案

您需要在条件之前使用if 而不是and:

>>> lx = [{'key1': 'foo'},  {'key1': 'foobar'}]
>>> ly = [{'key2': 'foo'},  {'key2': 'bar'}]
>>> [(a,b) for a in lx for b in ly and a['key1'] == b['key2']]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
UnboundLocalError: local variable 'b' referenced before assignment
>>> [(a,b) for a in lx for b in ly if a['key1'] == b['key2']]
[({'key1': 'foo'}, {'key2': 'foo'})]

关于python - 基于python中键值的2个字典列表中的2元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41656891/

相关文章:

python——在列表上应用 lstrip 的递归列表理解

python - 如何在 django+fastcgi+IIS 设置中销毁资源?

python - 在导入时指定 dtype 选项或设置 low_memory=False

python - 检测 tty 输出结束

python - 什么是按属性构建字典列表的 Pythonic 方法?

scala - 如何在列表中找到成绩最好的学生?

python - 如何在 Python 中检查 shell 命令是否结束

python Decimal - 检查是否为整数

python - 优化在一长串字符串中的搜索