我试图以编程方式创建包含n
相同子列表的列表:
>>> pos = [10,20]
>>> 3 * pos
[10, 20, 10, 20, 10, 20]
Run Code Online (Sandbox Code Playgroud)
但我想要的是 [[10,20], [10,20], [10,20]]
有线索吗?
[[10, 20] for x in range(3)]
Run Code Online (Sandbox Code Playgroud)
提防
[[10, 20]] * 3
Run Code Online (Sandbox Code Playgroud)
因为它复制相同的列表3次
使用列表理解:
[[10, 20] for _ in range(3)]
Run Code Online (Sandbox Code Playgroud)
还可以选择使用乘法:
[[10, 20]] * 3 # or [pos] * 3
Run Code Online (Sandbox Code Playgroud)
但这会创建一个包含 3 个对同一嵌套列表的引用的列表:
>>> lis = [[10, 20]] * 3
>>> lis[0][0] = 'foo'
>>> lis
[['foo', 20], ['foo', 20], ['foo', 20]]
Run Code Online (Sandbox Code Playgroud)
这通常不是你想要的。列表推导式会为每次循环迭代重新计算左侧的表达式(表达式之前的部分for
),并为外部列表中的每个索引创建一个新列表:
>>> lis = [[10, 20] for _ in range(3)]
>>> lis[0][0] = 'foo'
>>> lis
[['foo', 20], [10, 20], [10, 20]]
Run Code Online (Sandbox Code Playgroud)
如果您想使用存储在变量中的列表进行重复,请确保在每次迭代时创建一个副本:
[pos[:] for _ in range(3)]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
68 次 |
最近记录: |