使用相同的布尔值初始化列表

2022-01-18 00:00:00 python list initialization boolean

问题描述

没有循环是否可以将所有列表值初始化为某个布尔值?例如,我想要一个包含 N 个元素的列表,全部为 False.

Is it possible without loops initialize all list values to some bool? For example I want to have a list of N elements all False.


解决方案

你可以这样做:-

>>> [False] * 10
[False, False, False, False, False, False, False, False, False, False]

注意:-请注意,您永远不应该对具有相同值的 mutable typeslist 执行此操作,否则您会看到以下示例中的令人惊讶的行为:-

NOTE: - Note that, you should never do this with a list of mutable types with same value, else you will see surprising behaviour like the one in below example: -

>>> my_list = [[10]] * 3
>>> my_list
[[10], [10], [10]]
>>> my_list[0][0] = 5
>>> my_list
[[5], [5], [5]]

如您所见,您在一个内部列表中所做的更改会反映在所有列表中.

As you can see, changes you made in one inner list, is reflected in all of them.

相关文章