Python 根据条件生成子列表

3 投票
6 回答
17166 浏览
提问于 2025-04-17 12:30

我有三个列表,分别叫做 xyz,我用以下代码把它们画出来:

ax.plot3D(x, y, z, linestyle = 'None', marker = 'o').

有没有简单的方法只画出那些 x 大于 0.5 的点呢?

(我遇到的问题是,怎么在不使用循环的情况下,根据条件定义一个子列表。)

6 个回答

3

简单的列表推导式不足以去掉那些(x,y,z)的元组,如果x小于等于0.5的话,你需要做一些额外的工作。我在第二部分使用了operator.itemgetter

from operator import itemgetter

result = [(a, b, c) for a,b,c in zip(x,y,z) if a > 0.5] # first, remove the triplet
x = itemgetter(0)(result)  # then grab from the new list the x,y,z parts
y = itemgetter(1)(result)
z = itemgetter(2)(result)

ax.plot3D(x, y, z, linestyle="None, marker='o')

编辑: 根据@shenshei的建议,我们可以用一行代码来实现这个功能:

ax.plot3D(
  *zip(*[(a, b, c) for a,b,c in zip(x,y,z) if a > 0.5]), 
  linestyle="None, 
  marker='o'
)
6

我不太明白你为什么不想遍历这个列表,我猜测你是想把其他列表中相关的点也一起删除。

>>> x = [0.0, 0.4, 0.6, 1.0]
>>> y = [0.0, 2.2, 1.5, 1.6]
>>> z = [0.0, 9.1, 1.0, 0.9]
>>> zip(x,y,z)
[(0.0, 0.0, 0.0), (0.4, 2.2, 9.1), (0.6, 1.5, 1.0), (1.0, 1.6, 0.9)]
>>> [item for item in zip(x,y,z) if item[0] > 0.5]
[(0.6, 1.5, 1.0), (1.0, 1.6, 0.9)]

把这个列表分开成它里面的各个子列表,肯定是需要某种方式去遍历这个列表的。

4

要检查列表中每个元素的条件,至少得遍历一次这个列表,这是不可能避免的。你可以使用numpy,这样在条件满足后就能方便地访问这些元素,接着可以这样做:

 import numpy
 x = [0.0, 0.4, 0.6, 1.0]
 y = [0.0, 2.2, 1.5, 1.6]
 z = [0.0, 9.1, 1.0, 0.9]
 res = numpy.array([[x[i], y[i], z[i]] for i in xrange(len(x)) if x[i] > 0.5])
 ax.plot3D(res[:,0], res[:,1], res[:,2], linestyle="None, marker='o'")

撰写回答