python使用列表理解对dict的多级列表进行切片

标签 python list dictionary list-comprehension

我有 3 级深度列表,如下:

parent = [
   [
      {'x': 1, 'y': 2},
      {'x': 3, 'y': 8},
      .
      .
      .
   ],
   [
      {'x': 8, 'y': 5},
      {'x': 9, 'y': 6},
      .
      .
      .
   ]
]

我正在尝试使用列表理解将所有 x 放入一个列表中,将所有 y 放入另一个列表中

我尝试过这样的事情: [gc for gc in [c for c in [p.get('x') for p in Parent]]]

但是 get('x') 仍然命中列表而不是元素,主要是因为最内部的 []。知道如何实现这一目标吗?

最佳答案

不需要在这里列出推导式。

这是通过 operator.itemgetter 提供的功能解决方案和 itertools.chain :

from itertools import chain
from operator import itemgetter

parent = [[{'x': 1, 'y': 2},
           {'x': 3, 'y': 8}],
          [{'x': 8, 'y': 5},
           {'x': 9, 'y': 6}]]

x, y = zip(*map(itemgetter('x', 'y'), chain.from_iterable(parent)))

print(x)  # (1, 3, 8, 9)
print(y)  # (2, 8, 5, 6)

您也可以使用嵌套列表推导式:

x = [i['x'] for L in parent for i in L]
y = [i['y'] for L in parent for i in L]

请注意,嵌套推导式的顺序与常规 for 循环一致:

x = []
for L in parent:
    for i in L:
        x.append(i['x'])

关于python使用列表理解对dict的多级列表进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53767868/

相关文章:

python - python中图像数组的居中

list - 遍历图(可能有循环)并返回 Prolog 中的路径

python - dict.update() 是线程安全的吗?

Python:如何在一行中打印所有条件的结果

python - 无法部署 webpy 应用程序

python - 对上一行的两个值求和

c++ - QML map 可见区域

python - 变量赋值和修改(Python中)

Java程序将列表中给定数字的连续数字分组<list>

python - 根据其他两个词典的差异创建词典的最佳方法是什么?