Mayavi points3d渲染异常:生成20个点却渲染出更多点数
Here's my code:
import mayavi.mlab as mlab import numpy as np import random #white blackground mlab.figure(fgcolor=(0., 0., 0.), bgcolor=(1, 1, 1)) x1 = y1 = z1 = size1 = [] # number of points number = 21 for i in range(1,number): x1.append(random.randint(-10,11)) y1.append(random.randint(-10,11)) z1.append(random.randint(-10,11)) size1.append(i) #create spheres mlab.points3d(x1, y1, z1, size1, resolution=30) #render mlab.show()
I wanted to generate 20 points using a loop from 1 to 21 (range(1,21)), but the rendered output has way more than 20 points. What's going wrong here?
Answer
Let's cut to the chase: your list initialization is causing all four variables to point to the same underlying list.
When you write:
x1 = y1 = z1 = size1 = []
You're not creating four separate empty lists—you're creating one list, and making x1, y1, z1, and size1 all reference that single list. So every time you call append() on any of these variables, you're adding elements to that one shared list.
Let's walk through one loop iteration to see the impact:
- You append a random x-value to
x1→ shared list has 1 element - Then append a y-value to
y1→ shared list has 2 elements - Then append a z-value to
z1→ shared list has 3 elements - Then append the size to
size1→ shared list has 4 elements
After 20 full iterations, that shared list has 80 elements (20 * 4). When mlab.points3d() gets these lists, it uses their length to decide how many points to render—hence the extra points you're seeing.
The Simple Fix
Just initialize each list separately so they're distinct objects:
x1 = [] y1 = [] z1 = [] size1 = []
With this change, each append() only modifies the list you intended. After 20 iterations, each list will have exactly 20 elements, and you'll get the 20 points you expected in your render.
内容的提问来源于stack exchange,提问作者XuMuK

