2013-09-21 59 views
0

我已經編程了大約1周。列表索引超出範圍,但我重置索引(Python)

我正在寫一個簡單的程序來循環這個List並每次將變量加1。

我得到錯誤:列表索引超出範圍。

我相信這是因爲我的指數值太高? 而且走得太高之前,我重新索引值:

 index += 1 
     index and 7 

的邏輯,一旦它成爲> = 8應該重置指數爲0,不應該嗎?

在這種情況下,我不明白什麼是錯的。請參閱我的代碼:

lookups = [0,1,2,3,4,5,6,7] 
index = 0 
dword_C06748 = 0 

count = 0 

offset1 = 0 
rn_offset = 0 


def next_value(): 
    global lookups, index, count 
    while count < 18: 
     lookups[index] += 1 
     index += 1 
     index and 7 
     count += 1 

next_value() 
+1

你覺得呢'指數和7'呢? – tacaswell

+3

'index = index%8'對我來說似乎更符合邏輯。 – Aleph

+0

@tcaswell我認爲它執行一個邏輯與使用變量'索引'與7.因此,當索引= 8時,它將做8和7.答案是0,應該指定0索引。 – BBedit

回答

2

and是蟒蛇布爾AND,使用&對位與:

index &= 7 #index = index & 7 

由於整數是不可變的,你要的結果重新分配回index

3

index and 7不復位index。它只是計算一個沒有保存的布爾值。所以這個聲明沒有效果。代替使用index = index % 8。這可以確保指數總是會低於8

或者你可以使用

index = index % len(lookups) 
1

我會建議您使用:

if index >= 8: 
    index = 0 

index = index % 8 

或替代使用就地模數運算符

index %= 8 

正如它在Python的禪中所說(打開一個Python窗口並輸入import this),可讀性是很重要的。 這些選項比您的代碼的更正版本更具可讀性,請使用按位代替and,因此您應該使用它們。

1

我想下面將複製你的代碼的輸出更Python的方式:

lookups = [0,1,2,3,4,5,6,7] 

def next_value(): 
    # xrange returns the value 0, 1, ... 17 
    for count in xrange(18): # or just range if you are using py3 
     # the mod makes sure the index is always less than 8 
     lookups[count % 8] += 1 

next_value() 
+0

在Python 3.x中'範圍'而不是'xrange' – rlms

+0

對,我仍然是2.7。 – tacaswell