Python:更改嵌套列表的值 [英] Python: Changing values of a nested list

查看:44
本文介绍了Python:更改嵌套列表的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在使用嵌套列表来存储一些数据,并且无法更改子列表之一的特定值:

So I'm using a nested list to store some data and I'm having trouble with changing specific values of one of the sublists:

if attributes[3] == 'W':
    self.board[3][3] = 'W'

(数字是我用来测试的占位符)

(numbers are placeholders i'm using to test)

board是一个如下创建的类变量(我正在尝试创建一个由用户指定的网格,其输入的列和行大小构成了属性的前两个部分)

board is a class variable that is created as follows (I'm trying to create a grid as specified by a user, with their input for column and row sizes making up the first two parts of attributes)

self.board = []
rows = []
self.score = [0, 0]
for x in range(attributes[0]):
    rows.append('')
for y in range(attributes[1]):
    self.board.append(rows)

但是,每当我尝试更改子列表的值时,它都会更改同一索引的所有子列表的值:

However, whenever I try to change the value of a sublist, it changes the values for all sublists for that same index:

[['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', ''], ['', '', '', 'W', '', '', '', '']]

我不知道怎么了.有人有什么想法吗?

I can't figure out what's wrong. Anyone have any ideas?

推荐答案

我认为可以在这个非常简单的示例中说明其原因:

I think the reason for this can be demonstrated on this very simple example:

a = [1,2,3]

b = [a,a,a] # <- this is what you are actually doing

print(list(map(id,b)))
#[140475353832712, 140475353832712, 140475353832712]

请确保上面的所有ID都不相同.这意味着您正在列表中搜索,引用的对象相同.因此,更改一个存在项,将更改每个子列表.

Please not that all ids are same above. This means that you are stroning in your list, references to the same object. thus changing one subsist, changes every sublist.

但是,您应该执行此操作(或其他等效操作):

However, you should be doing this (or some equivalent):

b2 = [a[:], a[:], a[:]] #
print(list(map(id,b2)))
#[140475353832136, 140475353832072, 140475353832520]

请注意,每个子列表的ID不同.现在b2包含对不同子列表的引用.

Please note, different id for each sublist. Now b2 contains references to different sublists.

总而言之,您应该具有以下条件:

To sum up, you should have this:

for y in range(attributes[1]):
    self.board.append(rows[:])

这篇关于Python:更改嵌套列表的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆