在 Python 中初始化一个大的布尔值列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13771993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initializing a large list of booleans in Python
提问by flau
Possible Duplicate:
Initialize list with same bool value
可能的重复:
使用相同的 bool 值初始化列表
I'm attempting to make a prime number generator in python 2.7 and plan to use an array (or list) of booleans which will indicate whether a given number is prime.
我正在尝试在 python 2.7 中创建一个素数生成器,并计划使用一个布尔数组(或列表)来指示给定的数字是否为素数。
Let's say I wanted to initialize a list of 5000 booleans, how would I do so without having to manually type [True, True, ...]
假设我想初始化一个包含 5000 个布尔值的列表,我该怎么做而不需要手动输入 [True, True, ...]
采纳答案by arshajii
You could try this:
你可以试试这个:
[True] * 5000
Lists can be multiplied in Python (as can strings):
列表可以在 Python 中相乘(字符串也可以):
>>> [True] * 3
[True, True, True]
>>> "abc" * 3
'abcabcabc'
回答by lqc
I'm attempting to make a prime number generator in python 2.7 and plan to use an array (or list) of booleans which will indicate whether a given number is prime.
我正在尝试在 python 2.7 中创建一个素数生成器,并计划使用一个布尔数组(或列表)来指示给定的数字是否为素数。
This sounds really wasteful. A better approach would be to have a set()with only the numbers you need:
这听起来真的很浪费。更好的方法是set()只使用您需要的数字:
>>> primes = {2, 3, 5, 7}
>>> 4 in primes
False
>>> 5 in primes
True

