1

Why does this say list index out of range? This may not be the best way of doing this but just wondering why this is happening! Thanks

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
4

3 回答 3

6

Simeon Visser 的回答回答了您的问题,但我认为仍然值得指出 Pythonic 解决您的问题的方法:

from string import ascii_uppercase as uppercase

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

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

于 2013-11-10T21:13:13.663 回答
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

换句话说:你什么时候还在count通过添加一个来实现它。您可以通过将该行转换为来修复您的代码:2526while

while count < 25:
于 2013-11-10T21:04:23.780 回答
0

这就是发生错误的原因:

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

输出结束:

24
25
26

...并且字母[26] 超出范围,因为键必须低于 len(alphabet)。

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

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-loop和enumerate

于 2013-11-10T21:13:00.650 回答