简体   繁体   English

Python-在列表列表中更改元素

[英]Python- Changing element within a list of lists

I'm trying to change an element within a list of lists. 我正在尝试更改列表列表中的元素。 Here is my code and I'm using python version 3: 这是我的代码,我正在使用python版本3:

myboard = []

colList = []
#makes a 2D list/array of the rows and colums
for i in range(columns):
    colList.append(0)

for x in range(rows):
    myboard.append(colList)


myboard[0][1] = 999

print(myboard[0][1])

When I do this, it changes all the 1'th elements in each list to 999. Help please! 当我这样做时,它将每个列表中的所有第1个元素更改为999。请提供帮助!

your error is due the fact that colList is the pointer to a list and not a list itself. 您的错误是由于colList是指向列表的指针,而不是列表本身。 If you want to have "independent" list in each element of myboard you have to replace 如果要在myboard每个元素中都有“独立”列表,则必须替换
myboard.append(colList) with myboard.append(colList.copy()) myboard.append(colList)myboard.append(colList.copy())

In this way each element of myboard will be a copy of the list. 这样,myboard的每个元素将成为列表的副本。

Short Solution: 简短解决方案:


As Donbeo pointed out you must replace myboard.append(colList) with myboard.append(colList.copy) 正如Donbeo指出的那样,您必须将myboard.append(colList)替换为myboard.append(colList.copy)

Why: 为什么:


Because in python when you make a reference (with in bar) to any mutable object (lets call it foo) its a exact replica, forever. 因为在python中,当您对任何可变对象(称为foo)进行引用(带有in栏)时,它始终是一个精确的副本。 So for instance foo = [1,2,3] and bar = [foo, foo, foo] makes bar = [[1,2,3],[1,2,3],[1,2,3]] . 因此,例如foo = [1,2,3]bar = [foo, foo, foo]使得bar = [[1,2,3],[1,2,3],[1,2,3]] Now lets say you change foo to [3,2,1] then bar updates and becomes [[3,2,1],[3,2,1],[3,2,1]] . 现在假设您将foo更改为[3,2,1]然后bar更新并变为[[3,2,1],[3,2,1],[3,2,1]] So, what is wrong with bar[0][1] = 999 . 因此, bar[0][1] = 999 Well, bar[0] == foo therefore bar[0][1] == foo[1] . 好吧, bar[0] == foo因此, bar[0][1] == foo[1]
Now in python there's a easy fix! 现在在python中有一个简单的解决方法! Lists have a copy method which creates a replica that does not change when foo does. 列表具有一个copy方法,该方法创建一个副本,当foo更改时,副本不会更改。 For example foo = [1,2,3] and bar = [foo.copy, foo.copy] ; 例如foo = [1,2,3]bar = [foo.copy, foo.copy] now try bar[0][1] = 999 . 现在尝试bar[0][1] = 999 ITS ALIVE It works correctly. ITS ALIVE它可以正常工作。 Now bar[1][1] != bar[0][1] . 现在bar[1][1] != bar[0][1]

Demo 演示


Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM