我得到了这个错误:
Traceback (most recent call last):
File "D:/Python26/PYTHON-PROGRAMME/049 bam", line 9, in <module>
ball[i][j]=sphere()
NameError: name 'ball' is not defined当我运行这段代码时。但是球是定义的( balli=sphere() )。不是吗?
#2D-wave
#VPython
from visual import *
#ball array #ready
for i in range(5):
for y in range(5):
ball[i][j]=sphere()
timer = 0
dt = 0.001
while(1):
timer += dt
for i in range(5):
for y in range(5):
#wave equation
x = sqrt(i**2 + j**2) # x = distance to the source
ball[i][j].pos.y = amplitude * sin (k * x + omega * timer)
if timer > 5:
break发布于 2010-02-13 02:11:17
当你说ball[i][j]时,你必须已经有了一些对象ball,这样你才能索引(两次)它。请尝试此段:
ball = []
for i in range(5):
ball.append([])
for y in range(5):
ball[i].append(sphere())发布于 2010-02-13 02:10:53
不,未定义ball。您需要先创建一个list(),然后才能开始分配给列表的索引。类似地,需要在将嵌套列表分配给它们之前创建它们。试试这个:
ball = [None] * 5
for i in range(5):
ball[i] = [None] * 5
for j in range(5):
ball[i][j]=sphere()或者这样:
ball = [[sphere() for y in range(5)] for x in range(5)]使用两个列表理解的后一种语法更惯用--如果您愿意的话,它更像Pythonic式的语法。
发布于 2010-02-13 02:10:11
Python不知道ball是一个列表。在使用它之前(在第一个for循环中),您必须将它初始化为
ball = []所以Python知道把它当作一个列表来处理。
https://stackoverflow.com/questions/2254009
复制相似问题