nestedLists[2][4]=“a”将列表中每个列表的第5个成员设置为“a”

2024-09-24 02:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

在过去的几周里,我一直在学习python3。我遇到了一个障碍:

逻辑上,nestedLists[2][4]=“a”行应该将列表中第3个列表的第5个成员设置为“a”。不幸的是,由于我不明白的原因,它将列表中每个列表的第5个成员设置为“a”。这是我的代码:

gameList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]

def buildList(gameListt):
    gameListt[0] = ("~ " * 60).split()
    for i in range(len(gameListt)):
        gameListt[i] = gameListt[0]
    return gameListt


gameList = buildList(gameList)

print(gameList)
gameList[2][4] = "a"
print(gameList)

我完全迷路了。语法检查得很好,当我尝试以下方法时:

gameList = [["c","a","t"],["h","a","t"]]

gameList[0][2] = "b"
print(gameList)

它工作正常,输出“cab”和“hat”。我需要帮助!你知道吗

提前谢谢!你知道吗


Tags: 代码列表fordef原因成员逻辑python3
1条回答
网友
1楼 · 发布于 2024-09-24 02:25:41

gameList开始时是一个不同列表的列表,但是在这里:

for i in range(len(gameListt)):
    gameListt[i] = gameListt[0]

您正在使gameListt的每个元素都成为相同的列表

你应该这样做

def buildList(gameListt):
    for i in gameListt:
        i[:] = ["~"] * 60
    return gameListt

如果你像这样初始化游戏列表:

gameList = [[] for x in range(15)]

更容易看到它有15个子列表

相关问题 更多 >