没有循环是否可以将所有列表值初始化为某个布尔值?例如,我想要一个包含 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 types
的 list
执行此操作,否则您会看到以下示例中的令人惊讶的行为:-
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.
这篇关于使用相同的布尔值初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!