python - Python 中的 "List index out of range"错误

标签 python pygame

我又在做一个简单的西洋跳棋。而且,为了跟踪跳棋移动到的所有位置,我创建了一个列表来添加所有位置。

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/

相关文章:

python - Pygame 碰撞一次发生 19 次 - Python 3.x

python - 使用Python的过滤功能

python - 类型错误 : must be pygame. 表面,而不是元组。 Python/Pygame 菜鸟

python - 如何在保留python国际象棋中的移动堆栈的同时翻转棋盘?

python - 优化包含 8 个 for 循环的嵌套循环以最小化函数

python - Pygame 中的换行符在输入框中使用 Unicode

python - 如何使对象在按键时在对象数组中移动?

python - 那么为什么这个 Pygame move 代码可以工作,而这个却不行呢?

python - 是否可以将参数传递给 Django 模板中的模型类方法?

python - 计算日期之间的天数,使用 pyspark 忽略周末