初始化与同一布尔值列表
问题描述:
是否有可能没有循环初始化所有列表值一些布尔?例如,我想有N个元素的列表,全是假的。
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.
答
您可以做到这一点是这样的: -
You can do it like this: -
>>> [False] * 10
[False, False, False, False, False, False, False, False, False, False]
注: -
需要注意的是,你永远不应该以 可变类型
具有相同价值的列表做到这一点,否则你会看到令人惊讶的行为像在下面的例子: -
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.