Python 中快速嵌套列表的意外更新结果 [英] Unexpected update result on the quickly nested list in Python

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

问题描述

为什么不能更新下面的第一个元素而是整列?

<预><代码>>>>x=2*[2*[1]]>>>X[[1, 1], [1, 1]]>>>x[0][0]=2>>>X[[2, 1], [2, 1]]

解决方案

尽管这是一个明显的重复,但使用 range:

<预><代码>>>>x=[[1 for i in range(2)] for x in range(2)]>>>X[[1, 1], [1, 1]]>>>x[0][0]=2>>>X[[2, 1], [1, 1]]>>>

至少还能做到:

<预><代码>>>>x=[[1]*2 for x in range(2)]>>>x[0][0]=2>>>X[[2, 1], [1, 1]]>>>

Why couldn't the first element but the whole column be updated below?

>>> x=2*[2*[1]]
>>> x
[[1, 1], [1, 1]]
>>> x[0][0]=2
>>> x
[[2, 1], [2, 1]]

解决方案

Even tho this is a clear duplicate but use range:

>>> x=[[1 for i in range(2)] for x in range(2)]
>>> x
[[1, 1], [1, 1]]
>>> x[0][0]=2
>>> x
[[2, 1], [1, 1]]
>>> 

At least still able to do:

>>> x=[[1]*2 for x in range(2)]
>>> x[0][0]=2
>>> x
[[2, 1], [1, 1]]
>>> 

这篇关于Python 中快速嵌套列表的意外更新结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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