2014-01-30 28 views
-2

我正在尝试打印'col_1'内部存储的第5个值。当我去打印第5个值,或使用它,它给了我这个错误:列表索引超出范围错误,但值是否存在?

Traceback (most recent call last): 
File "/home/pi/test_files/test_two.py", line 99, in <module> 
print(col_1[5]) 
IndexError: list index out of range 

但是,如果我尝试值1,4它是完全正确的?我有代码,将条目放入这些列表中:

def do_query(): 
    connection = sqlite3.connect('test_db.db') 
    cursor = connection.cursor() 
    cursor.execute("SELECT PRODUCT,BIN,SIZE,COLOR FROM TESTER_6 ORDER BY CheckNum") 
    records = cursor.fetchall() 
    print(records) 

    for(Product,Bin,Size,Color) in records: 
     col_1.append(Product) 
     col_2.append(Bin) 
     col_4.append(Size) 
     col_3.append(Color) 

    connection.commit() 
    cursor.close() 
    connection.close() 

当我打印'记录'时,有第5个条目。不知何故,它在for循环中没有进入列表。

为什么我有这个问题?

+0

不能肯定地告诉如果这是你在做的错误,但你知道,名单都是用Python 0索引?第一个元素在'list [0]'和第五个元素在'list [4]'。 – xbonez

回答

4

最喜欢的语言,Python的指数为0。

start如果在列表中有五行,呼吁col_1[5]会给出一个IndexError。相反,列表中的第五个元素是col_1[4]

col_1 = ['a', 'b', 'c', 'd', 'e'] 
index: 0 1 2 3 4 

因此,在Python

>>> col_1[5] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
IndexError: list index out of range 
>>> col_1[4] 
'e' 
>>> col_1[0] 
'a' 
3

列表,像大多数语言,从0开始。所以即使有5个元素,也没有element[5]。如果你开始与1,你缺少的元素实际上是指数0

>>> range(5) 
[0, 1, 2, 3, 4] 
相关问题