我有 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/