我又在做一个简单的西洋跳棋。而且,为了跟踪跳棋移动到的所有位置,我创建了一个列表来添加所有位置。
Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), \
(370, 10), (430, 10), (10, 70), (130, 70), (190, 70), (250, 70), \
(310, 70), (370, 70), (430, 70), (10, 130), (70, 130), (130, 130), \
(190, 130), (250, 130), (310, 130), (370, 130), (430, 130), \
(10, 190), (70, 190), (130, 190), (190, 190), (250, 190), (310, 190), \
(370, 190), (430, 190)]
但是,当我尝试执行该程序时,我总是得到: Ld8 = Locations[31] - 列表索引超出范围
所以,我想也许一个列表只能包含一定数量的数字。因此,我创建了第二个 Locations 列表并添加了 E - H 行,以便拆分列表。但是,我仍然收到索引超出范围的相同错误。 (ld8是存储D行第8列位置的变量)
最佳答案
你有一个非常基本的理解问题:
>>> Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), (370, 10), (430, 10), (10, 70), (130, 70), (190, 70), (250, 70), (310, 70), (370, 70), (430, 70), (10, 130), (70, 130), (130, 130), (190, 130), (250, 130), (310, 130), (370, 130), (430, 130), (10, 190), (70, 190), (130, 190), (190, 190), (250, 190), (310, 190), (370, 190), (430, 190)]
>>> len(Locations)
31
>>> Locations[0] # first element
(10, 10)
>>> Locations[30] # last element
(430, 190)
>>> Locations[31] # doesn't exist!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Locations 中的元素从 0 到 30,因为总共有 31 个元素。
关于python - Python 中的 "List index out of range"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7756069/