2017-02-22 60 views
0

我想通过我创建的数组的每个元素。但是,我正在做一些调试,事实并非如此。以下是我目前为止的内容以及打印出的内容。阵列中的打印元素python问题

def prob_thirteen(self): 
     #create array of numbers 2-30 
     xcoords = [range(2,31)] 
     ycoords = [] 

     for i in range(len(xcoords)): 
      print 'i:', xcoords[i] 

输出:

i: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] 

为什么 '我' 回到我的整个阵列,而不只是第一个元素:2?我不知道为什么这会返回我的整个阵列。

回答

2
xcoords = [range(2,31)] 

这条线将创建长度1.该数组中的唯一的元件的阵列是数字2的阵列 - > 30.你的循环正在打印数组的元素。更改该行:

xcoords = range(2,31) 

这个答案就是Python 2正确的,因为range function返回一个列表。 Python 3将返回一个range对象(可以重复生成所需的值)。以下行应在Python 2和3的工作:

xoords = list(range(2,31)) 
+0

啊难怪,非常感谢你! – helloworld

0

首先,改变xcoords所以它不是一个列表内的列表:

xcoords = range(2, 31) 

我们并不需要遍历在列表中使用len(xcoords)使用列表中的索引。在蟒蛇我们可以简单地遍历像这样的列表:

for coord in xcoords: 
    print "i: ", coord 

如果我们需要跟踪的指数,我们可以使用enumerate

for i, coord in enumerate(xcoords): 
    print str(i) + ":", coord