Skip to main content
 首页 » 编程设计

python之有什么比当前方法更快生成 newlist.append(q) 列表的建议吗

2024年10月01日27kuangbin

您好,我正在尝试使用下面提到的代码生成元素列表 q。

newlist=[] 
coords=pn['point.coords'][z>=0.001950] 
points=range(27000) 
for q in points: 
    if pn['point.coords'][q] in coords:  
        newlist.append(q) 

这里 pn['point.coords'] 是点的 x ,y ,z 坐标列表,我想在其中 z>= 0.001950。 x,y,z 的总限制是从 0 到 0.002。代码运行缓慢。有没有更快的方法来获取这个新列表?

请您参考如下方法:

参见 np.where . numpy 的方式是

coords = pn['point.coords'] 
z = coords[:,2] 
q, = np.where(z>0.001950) 
high_points=coords[q] 

另外一点,这是一个线性时间程序。 你的是二次方的,因为 p in coords 有一个隐藏的复杂性。 zmax 的值很小,执行时间会迅速增加。