有时候我们需要初始化一个嵌套着几个列表的列表,这种情况下推荐使用列表推导式
代码1:
def test01():
l = [["_"] * 3 for i in range(3)]
print(l)
l[1][2] = "x"
print(l)
if __name__ == '__main__': test01()
执行结果
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
[['_', '_', '_'], ['_', '_', 'x'], ['_', '_', '_']]
代码2:这种看着便捷,但实际上是错误的方式,外层列表里面实际上存的是3个指向同一个引用的列表,修改任一一个则全都被修改
def test02():
l = [["_"]*3]*3
print(l)
l[1][2] = "x"
print(l)
if __name__ == '__main__':
test02()
执行结果
[['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
[['_', '_', 'x'], ['_', '_', 'x'], ['_', '_', 'x']]
上面两种代码的等价效果:
代码一相当于:
def test_11():
l = []
for i in range(3):
row = ["_"]*3
l.append(row)
print(l)
l[1][2] = "x"
print(l)
if __name__ == '__main__':
test_11()
代码二相当于:
def test_22():
l = []
row = ["_"] * 3
for i in range(3):
l.append(row)
print(l)
l[1][2] = "x"
print(l)
if __name__ == '__main__':
test_22()