python空列表技巧 [英] python empty list trick
本文介绍了python空列表技巧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
Python列表混乱
Possible Duplicate:
Python list confusion
关于Python列表,我有一个小问题:
I've got one little question about Python lists:
为什么会这样?
x = [[]] * 4
x[0].append('x') -> [['x'], ['x'], ['x'], ['x']]
推荐答案
[]
的同一实例正在复制,因此当您将第一个'x'
追加到第一个'x'
时,实际上将其追加到所有-因为都是同一个对象!
the same instance of []
is being duplicated, so when you append to the first one 'x'
, you actually append it to all - because they are all the same object!
正确的方法是每次都明确创建一个新的列表实例:
The right way to do it is to explicitly create a new list instance each time:
x = [[] for _ in range(4)]
这篇关于python空列表技巧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文