Skip to main content
 首页 » 编程设计

python之获取 Python 列表中重复值的范围

2025年05月04日9EasonJim

我有一个 Python 列表,表示一系列线段,其中包含形式为 (x, y, z, color) 的元组,其中 x、y、z 是 float ,color 是描述线应该是什么颜色的字符串在。我(或者更确切地说,我正在使用的 mecode 库)将坐标粘贴到 numpy 数组 X、Y 和 Z 中。

当我在 matplotlib 中渲染这个列表时:

from mpl_toolkits.mplot3d import Axes 
import matplotlib.pyplot as plt 
fig = plt.figure() 
ax = fig.gca(projection='3d') 
ax.plot(X, Y, Z) 

3D 查看器表现相当不错,但当然我看不到任何颜色。

但是当我使用 Line colour of 3D parametric curve in python's matplotlib.pyplot 建议的代码时:

for i in range(len(X)-1): 
    ax.plot(X[i:i+2], Y[i:i+2], Z[i:i+2],  
            color=self.position_history[i][3]) 

在 3D 渲染中速度变得更慢。

我想知道迭代具有相同颜色的列表元素的最佳 Pythonic 方法是什么,这样我就可以减少对 ax.plot 的调用次数。我假设这会让事情变得更快。

请您参考如下方法:

如果重复调用 plot 是问题所在,那么如果您按颜色对所有点进行分组并将它们全部渲染在一起,您将获得加速。执行此操作的一种方法(快速而肮脏,以便您可以检查这是否会使您的渲染速度更快)在这里:

from collections import defaultdict 
points = defaultdict(list) # will have a list of points per color 
 
for i in range(len(X)): 
    color = self.position_history[i][3] 
    if len(points[color])==0: 
        points[color].append([]) # for the X coords 
        points[color].append([]) # for the Y coords 
        points[color].append([]) # for the Z coords 
    points[color][0].append(X[i]) 
    points[color][1].append(Y[i]) 
    points[color][2].append(Z[i]) 
 
# now points['red'] has all the red points  
 
for color in points.keys(): 
    pts = points[color] 
    ax.plot(pts[0],pts[1],pts[2],  
        color=color)