gpt4 book ai didi

python - 类型错误,因为列表索引必须是整数或切片,而不是元组

转载 作者:太空宇宙 更新时间:2023-11-03 14:35:31 25 4
gpt4 key购买 nike

我已尽力寻找解决数组和元组问题的方法,但我找不到任何对我有帮助的东西。这就是问题所在:

类型错误:列表索引必须是整数或切片,而不是元组

我正在创建一个基于文本的游戏,我在数组中使用数组来制作 map :

maps = [
[
#Room 1
['0','0','0','0','0'],
['0','x','.','x','0'],
['0','x','x','x','0'],
['0','.','x','.','0'],
['0','0','0','0','0']
]
[
#Room 2
['0','0','0','0','0'],
['0','.','x','.','0'],
['0','x','x','x','0'],
['0','.','.','x','0'],
['0','0','0','0','0']
]
]

不幸的是,最后一个数组给了我 TypeError: 类型错误:列表索引必须是整数或切片,而不是元组代码如下所示:

['0','0','0','0','0']

我做错了什么?

最佳答案

您错过了两者之间的逗号 sub-arrays这导致 Python 将此误解为您 indexing第一个array与第二个array .

我很确定这就是您想要做的:

maps = [
[
#Room 1
['0','0','0','0','0'],
['0','x','.','x','0'],
['0','x','x','x','0'],
['0','.','x','.','0'],
['0','0','0','0','0']
],
[
#Room 2
['0','0','0','0','0'],
['0','.','x','.','0'],
['0','x','x','x','0'],
['0','.','.','x','0'],
['0','0','0','0','0']
]
]

此外,您还用 array 标记了该问题,但您在这里定义的是 list 。如果您想要numpy array ,你可以这样定义:

maps = np.array([
[
#Room 1
['0','0','0','0','0'],
['0','x','.','x','0'],
['0','x','x','x','0'],
['0','.','x','.','0'],
['0','0','0','0','0']
],
[
#Room 2
['0','0','0','0','0'],
['0','.','x','.','0'],
['0','x','x','x','0'],
['0','.','.','x','0'],
['0','0','0','0','0']
]
])

关于python - 类型错误,因为列表索引必须是整数或切片,而不是元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com