由于 TypeError,无法将嵌套列表值替换为 X:列表索引必须是整数或切片,而不是列表错误 [重复]

问题描述 投票:0回答:1

我正在尝试做一个学习Python嵌套列表的练习,它的工作方式是你有一个网格,然后根据你输入的内容,它会用“X”替换该位置。您还需要在输入 2 位数字时执行此操作。我能够将输入转换为列表,并能够确保它们也是整数。

# 🚨 Don't change the code below 👇
row1 = ["⬜️","️⬜️","️⬜️"]
row2 = ["⬜️","⬜️","️⬜️"]
row3 = ["⬜️️","⬜️️","⬜️️"]
map = [row1, row2, row3]
print(f"{row1}\n{row2}\n{row3}")
position = input("Where do you want to put the treasure? ")
# 🚨 Don't change the code above 👆

#Write your code below this row 👇


#Take the 2-digit number and split into the column and row numbers
#Also now integers to find the indexes
column_num = int(position[0])
row_num = int(position[1])

#Take the 2 numbers, and use to make where to mark the X
new_list = [column_num, row_num]
new_column = new_list[0]
new_row = new_list[1]
x = [new_column] + [new_row]
print(new_list)
print(x)

# Replace the new_list list, which have the indexes, into X
map[new_list] = "X"

#Write your code above this row 👆

# 🚨 Don't change the code below 👇
print(f"{row1}\n{row2}\n{row3}")

我收到此错误:

Traceback (most recent call last):
  File "C:\Users\*******\IdeaProjects\_100DaysOfCodev2\.idea\Day 4 - Beginner - Randomisation and Python Lists\6- [Exercise] - Treasure Map.py", line 27, in <module>
    map[new_list] = "X"
TypeError: list indices must be integers or slices, not list

我尝试将列表更改为“int”,但它告诉我不是元组而不是列表。

有人有什么想法吗?我想了解我在这里缺少什么,而不是回去玩解决方案。

我尝试分离新列表的值,以便它们成为整数,但我需要它们成为一组索引,但它不起作用,因为它再次变成列表。我尝试从“地图”嵌套列表中召唤不同的东西,但我收到索引错误,它也超出了索引范围。而且我们还没有处于“for, in”状态或定义函数状态。回溯(最近一次调用最后一次): 文件“C:\Users 792977\IdeaProjects_100DaysOfCodev2.idea\Day 4 - 初学者 - 随机化和 Python 列表 - [练习] - Treasure Map.py”,第 27 行,位于 地图[新列表] = "X" 类型错误:列表索引必须是整数或切片,而不是列表

python list typeerror nested-lists index-error
1个回答
0
投票

您需要明确识别 2 个索引:

map[new_list[0]][new_list[1]]
© www.soinside.com 2019 - 2024. All rights reserved.