另外我的另一篇文章.如果我有一个坐标列表,我如何将它们分配给变量并继续追加和分配:
positions = [(1,1), (2,4), (6,7)]
index = 0
for looper in range(0, len(positions)):
posindex = positions[index]
index = index + 1
Run Code Online (Sandbox Code Playgroud)
其中posindex是pos0,然后是pos1,然后是pos2并随着变量索引而增加,这也将给出列表中的索引.Python给了我这个:
"'posindex' is undefined"
Run Code Online (Sandbox Code Playgroud)
无论如何将变量放入另一个变量?我可能遇到的任何其他问题?
这段代码工作得很好.但是,有一个更好的方法:
positions = [(1,1), (2,4), (6,7)]
for posindex in positions:
# do something with posindex, for example:
print (posindex)
Run Code Online (Sandbox Code Playgroud)
哪个输出
(1, 1)
(2, 4)
(6, 7)
Run Code Online (Sandbox Code Playgroud)
您不需要循环索引 - Python可以简单地遍历列表.如果由于某些其他原因确实需要索引,请按照以下方式在Python中执行此操作:
for index, posindex in enumerate(positions):
print ("{0} is at position {1}".format(posindex, index))
Run Code Online (Sandbox Code Playgroud)