关于参考的python列表 [英] Regarding python list with reference

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

问题描述

以下是示例,

>>> x = ["a","b","c"]
>>> yy = [x] * 3
>>> yy
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]
>>> yy[0][0] = 'A'
>>> yy
[['A', 'b', 'c'], ['A', 'b', 'c'], ['A', 'b', 'c']]
>>>

当我执行yy[0][0] = 'A'时,它替换为子列表的所有第一个元素.我从这里得到的是当我执行[x] * 3时,它创建了对列表x的引用,但不确定其工作原理.可以请人解释一下.

When i do yy[0][0] = 'A', it replaced to all the first element of the sub-list. What i got from here is when i do [x] * 3, it creates some reference to list x but not sure how really it works. Could some one please explain.

非常感谢. 詹姆斯

推荐答案

[x]*3创建对同一列表的3个引用.您必须创建三个不同的列表:

[x]*3 creates 3 references to the same list. You have to create three different lists:

>>> yy = [list('abc') for _ in range(3)]
>>> yy[0][0]='A'
>>> yy
[['A', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c']]

第一行使用循环3次的列表理解来创建新列表.

The first line creates a new list using a list comprehension that loops 3 times.

使用id(),您可以看到相同的列表引用已重复:

Using id(), you can visualize that the same list reference is duplicated:

>>> x=list('abc')
>>> id(x)
67297928                                  # list object id
>>> yy=[x]*3                              # create a list with x, duplicated...
>>> [id(i) for i in yy]
[67297928, 67297928, 67297928]            # same id multipled
>>> yy = [list('abc') for _ in range(3)]  
>>> [id(i) for i in yy]
[67298248, 67298312, 67297864]            # three different ids

这篇关于关于参考的python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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