2012-03-03 154 views
0

此外到my other post。 如果我有坐标的名单,我怎么能并将其分配给变量,并保持追加和分配:如何在另一个变量的名称中使用变量?

positions = [(1,1), (2,4), (6,7)] 
index = 0 
for looper in range(0, len(positions)): 
    posindex = positions[index] 
    index = index + 1 

哪里posindex是POS0,然后POS1,然后POS2与可变折射率,这会给我增加列表中的索引也是如此。 Python给了我这个:

"'posindex' is undefined" 

无论如何把变量放入另一个? 我可能遇到的其他问题?

+4

我不认为该错误实际上是由该段代码引起的。 – 2012-03-03 21:02:06

+0

你为什么要这样做?为什么不使用位置[0]而不是'pos0'? – Amber 2012-03-03 21:03:54

+3

你需要掌握一本好的入门教科书并开始阅读。你目前的学习方法远非最佳。 – 2012-03-03 21:06:04

回答

8

此代码工作得很好。然而,有一个更好的办法:

positions = [(1,1), (2,4), (6,7)] 
for posindex in positions: 
    # do something with posindex, for example: 
    print (posindex) 

其输出

(1, 1) 
(2, 4) 
(6, 7) 

你不需要一个循环索引 - Python可以简单地遍历列表。如果你确实需要索引的其他原因,这里是你如何在Python中做到这一点:

for index, posindex in enumerate(positions): 
    print ("{0} is at position {1}".format(posindex, index)) 
相关问题