2014-01-30 30 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] 
相關問題