关于python的list.

一碗粥 发布于 2019/07/06 12:52
阅读 301
收藏 0

In [161]: # %load 53
...: a = [[]] * 5
...: print(a)
...: for i in range(5):
...:     a[i].append(9) 
...:     a[i] = a[i] * 5
...: print(a)
...:
[[], [], [], [], []]
[[9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]]

加载中
0
一碗粥
一碗粥

结果不应该是

[[9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9], 
[9, 9, 9, 9, 9]]

这个吗?

0
一碗粥
一碗粥

搞清楚了

a = [[]] * 5产生的结果[[], [], [], [], []],其实是一个地址。

而a[i] = a[i] * 5的操作会重新分配地址

0
o
osc_16818661

a = [[]] * 5

for i in range(5):

    a[i].append(9)

print(a)

 

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部