解开重复创建的嵌套列表? [英] Untie nested lists created by repetition?

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

问题描述

我想通过重复一个简单列表来创建嵌套列表,例如

I want to create a nested list by a repetition of a simple list, say

x = ['a','b','c']
y = [x] * 3

这将导致

[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

当我更改一个嵌套列表中的一个元素时,所有其他列表中的相应元素也会更改:

When I change an element of one of the nested lists, the corresponding elements in all other lists also change:

y[0][0] = 'z'

[['z', 'b', 'c'], ['z', 'b', 'c'], ['z', 'b', 'c']]

我该怎么做才能获得以下列表,而不是所有列表项中的上述更改?

What should I do in order to get the following list instead of the above change in all list items?

[['z', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

推荐答案

列表是python中的引用.因此,您将以x列表的方式编写对x列表的3个引用的列表.有几种方法可以解决此问题,并制作列表的真实副本,切片就是其中一种. Slice将根据切片范围从主列表中返回一个新列表.

Lists are references in python. Therefore you're making a list of 3 references to the x list with your code the way it is. There are several ways to work around this, and make a real copy of your list, slice is one of them. Slice will return a new list from the primary list based on the slice range.

下面,我仅使用循环来循环所需的次数(3),并每次都对x列表的整个范围进行切片,因此我将其返回.然后,我只将结果切片添加到y列表中.

Below I simply use loop to loop the number of times you wanted (3) and slice the full range of the x list each time so I return a copy of it. I then just append the resulting slice to the y list.

也许不是最漂亮的,但解决了这个问题.

Maybe not the prettiest, but solves this problem.

x = ['a','b','c']
y = []
for n in range(3):
    y.append(x[:])

print(y)

y[0][0] = 'z'

print(y)

输出:

[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
[['z', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

这篇关于解开重复创建的嵌套列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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