获取Python列表中重复值的范围
我有一个Python列表,它表示一系列线段,其中包含形式为(x,y,z,color)的元组,其中x,y,z是浮点数,color是一个字符串,描述线条应该是什么颜色。我(或者更确切地说,我正在使用的mecode库)将坐标粘贴到numpy数组X、Y和Z中 在matplotlib中呈现此列表时,使用:获取Python列表中重复值的范围,python,matplotlib,Python,Matplotlib,我有一个Python列表,它表示一系列线段,其中包含形式为(x,y,z,color)的元组,其中x,y,z是浮点数,color是一个字符串,描述线条应该是什么颜色。我(或者更确切地说,我正在使用的mecode库)将坐标粘贴到numpy数组X、Y和Z中 在matplotlib中呈现此列表时,使用: from mpl_toolkits.mplot3d import Axes import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca
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查看器的性能相当好,但我当然没有任何颜色
但当我使用以下建议的代码时:
在3D渲染中,速度会慢得多
我想知道Pythonic的好方法是迭代具有相同颜色的列表元素,以便减少对ax.plot的调用次数。我假设这将使事情更快。如果重复调用绘图是问题所在,那么如果按颜色将所有点分组并一起渲染,您将获得加速。实现此目的的一种方法(快速且脏,以便您可以检查这是否会使渲染速度更快)如下所示:
你可以将颜色添加到字典中,每次你得到一种颜色时,你都要检查它是否存在于字典中,如果存在,你就跳过它,否则你就迭代它
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])
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)