如何正确使用 b = [[1]*3]*3 ?
所有,
代码:
#=A===================
>>> b = [[1]*3]*3
>>> b
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> b[0][0] = 0
>>> b
[[0, 1, 1], [0, 1, 1], [0, 1, 1]]
>>>
#=B===================
>>> b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> b[0][0] = 0
>>> b
[[0, 1, 1], [1, 1, 1], [1, 1, 1]]
我可以使用类似于 "b = [[1]*3]*3" 的格式来获得与 "b = [[ 相同的行为1, 1, 1], [1, 1, 1], [1, 1, 1]]" 来减少输入?
as "b = [[1]*3]*3" 可能会返回一个基于“参考”的列表,这对日常工作有用吗?任何示例?
谢谢! 肯尼迪
All,
code:
#=A===================
>>> b = [[1]*3]*3
>>> b
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> b[0][0] = 0
>>> b
[[0, 1, 1], [0, 1, 1], [0, 1, 1]]
>>>
#=B===================
>>> b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
>>> b[0][0] = 0
>>> b
[[0, 1, 1], [1, 1, 1], [1, 1, 1]]
Can I use the format may looks like "b = [[1]*3]*3" to get the same behavior as the "b = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]" to reduce type in?
as "b = [[1]*3]*3" may return a "reference" based list, is it useful for daily works? any sample?
Thanks!
KC
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码的问题在于它引用了相同的列表,因此当您执行
b[0][0] = 0
时,您实际上是在更新引用处的值(其中所有三个数组都指向到)。为了获得所需的结果,我会这样做(使用 列表理解):
它实际上重新创建了一个列表,因此它引用了不同的列表,而不是答案中的相同列表。
b = [[1]*3 for _ in range(3)]
相当于:The problem with your code is that it references the same list, so when you do
b[0][0] = 0
, you are really updating the value at the reference(in which all three arrays point to).To get the desired results, I would do(using list comprehension):
which actually recreates a list, so it references different lists, rather than the same one in your answer.
b = [[1]*3 for _ in range(3)]
is equivalent to:您可以使用列表理解来构建列表:
You could build your list with a list comprehension instead:
您的问题是
[[1, 1, 1]] * 3
创建了对同一[1, 1, 1]
列表的三个引用的列表。要执行您想要的操作,您必须使用list()
或使用切片表示法创建 [1, 1, 1] 的副本:或者
要在一行中完成上述操作,您可以这样做:
Your problem is that
[[1, 1, 1]] * 3
creates a list of three references to the same[1, 1, 1]
list. To do what you want, you have to create copies of [1, 1, 1] usinglist()
or using slice notation:or
To do the above in one line, you could do this:
在A部分:
您有一个包含 3 个项目的列表,但所有项目都指向一个对象:
像这样:
但是在 B 部分,您有一个包含不同项目的列表
At section A:
you have a list with 3 items, but all items points to one object:
like this:
But at the section B , you have a list with different items