为什么这个迷你程序说列表索引超出范围?

时间:2013-11-10 20:59:47

标签: python list debugging

为什么这会说列表索引超出范围?这可能不是最好的方法,但只是想知道为什么会这样!感谢

key = 13    

alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

replacement_set = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

count = -1

while count <= 25:
    count += 1
    if count < int(key):
        index_value = int(count + int(key))
        replacement_set[index_value] = alphabet[count]
        print replacement_set
    elif count >= int(key):     
        index_value = int(count - int(key))
        replacement_set[index_value] = alphabet[count]
        print replacement_set
    else:
            break

print replacement_set

3 个答案:

答案 0 :(得分:6)

Simeon Visser的回答回答了你的问题,但我认为值得指出Pythonic解决你的问题:

from string import ascii_uppercase as uppercase

replacement_set = uppercase[13:] + uppercase[:13]

uppercase[:13]是切片表示法的一个示例。您可以从the Python documentation了解更多相关信息。

答案 1 :(得分:4)

IndexError发生在这里:

elif count >= int(key):     
    index_value = int(count - int(key))
    replacement_set[index_value] = alphabet[count] # <<<<<

因为count的值为26而发生这种情况。换句话说,您正在尝试访问超出alphabet范围的元素。请注意,您的循环不会阻止此操作,因为您在此处添加了1

while count <= 25:
    count += 1

换句话说:当count25时,您仍然会通过添加一个来26。您可以将while行转换为:

来修复代码
while count < 25:

答案 2 :(得分:0)

发生错误的原因:

while count <= 25:
    count += 1
    print count

结束输出:

24
25
26

...而字母[26]超出范围,因为密钥必须低于len(字母)。

使用应该使用类似的东西:

key = 13
for count, letter in enumerate(alphabet):
    # calculate index_value, so it has to be in correct range
    index_value = (count - key) % len(alphabet)
    replacement_set[index_value] = letter
    print replacement_set

(更多pythonic使用for - 循环和enumerate