【问题标题】:nestedLists[2][4] = "a" sets the 5th member of EVERY list in the list to "a" [duplicate]nestedLists[2][4] = "a" 将列表中每个列表的第 5 个成员设置为 "a" [重复]
【发布时间】:2013-03-21 11:41:20
【问题描述】:

过去几周我一直在学习 Python 3。我遇到了一个障碍:

从逻辑上讲,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”。我需要帮助!

提前致谢!

【问题讨论】:

  • 当您循环访问 gameListt 时,您正在创建对同一个列表的引用,而不是新列表。
  • 您可以改用:return [("~ " * 60).split() for i in range(len(gameListt))]

标签: python list python-3.x variable-assignment nested-lists


【解决方案1】:

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

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

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

你应该这样做

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

如果你像这样初始化gameList:

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

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

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多