Skip to main content
 首页 » 编程设计

python之如何在 python 中使用列表理解等于多个变量

2025年05月04日21lvdongjie

假设我有以下元素

_example = namedtuple('example',['x','y']) 

我收集了一堆这样的例子

examples = magic_function_that_returns_a_list_of_examples() 

我想替换下面两行

xs = [ e.x for e in examples] 
ys = [ e.y for e in examples] 

类似于此...

xs,ys  = [ [e.x,e.y] for e in examples] 

换句话说,是否可以利用列表推导式同时设置两个变量?

请您参考如下方法:

你可以只转置 namedtuple 的列表并解压它:

xs, ys = zip(*examples) 

例如:

from collections import namedtuple 
 
example = namedtuple('example',['x','y']) 
examples = [example(i, j) for i in range(5) for j in range(5)] 
 
xs, ys = zip(*examples) 
print(xs) 
print(ys) 

输出:

(0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4) 
(0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4) 

任何带有列表理解的解决方案都是不必要的复杂,最好用您提供的两个列表理解代替。如果您想在一行中完成,最清晰和最易读的列表推导方式是

xs, ys = [e.x for e in examples], [e.y for e in examples] 

但是,在我看来,zip(*examples) 可能仍然更好。