python中的list的*运算使用过程中遇到的问题

本文探讨了使用Python创建多个空列表时出现的一个常见错误——所有列表元素实际上是同一个对象。通过示例说明了这个问题,并提供了解决方案,即使用列表推导式来创建独立的列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目的:

想生成一个[[],[],[]] 这样的列表,

所以就 [[]]*3 这样做了,但是这样做会有问题,这样list中的三个list其实是同一个list。

例如:a=[[]]*3,然后a[0].append(1),

然后a就变成这样了:[[1],[1],[1]]

验证一下,发现表达式 a[0] is a[1] 的值为True。

如何解决呢,可以用列表生成器:a=[[] for i in range(3)]

这应该像是值类型和引用类型的区别,但是翻看python的文档时没发现有类似的说法,不过在翻看文档时发现里面提到了这个情形:

https://docs.python.org/3.6/library/stdtypes.html

内容摘录如下:

Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:

>>>
>>> lists = [[]] * 3
>>> lists
[[], [], []]
>>> lists[0].append(3)
>>> lists
[[3], [3], [3]]

What has happened is that [[]] is a one-element list containing an empty list, so all three elements of [[]] * 3 are references to this single empty list. Modifying any of the elements of lists modifies this single list. You can create a list of different lists this way:

>>>
>>> lists = [[] for i in range(3)]
>>> lists[0].append(3)
>>> lists[1].append(5)
>>> lists[2].append(7)
>>> lists
[[3], [5], [7]]

 

转载于:https://www.cnblogs.com/vanwoos/p/9217130.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值