Python 中的布尔列表初始化
在某些情况下,我们需要获取一个仅包含布尔值(如 true 和 false)的列表。本文介绍如何创建一个仅包含布尔值的列表。
使用范围
我们使用 range 函数,该函数给出所需的值的数量。使用 for 循环,我们根据需要将 true 或 false 分配给列表。
示例
res = [True for i in range(6)]
# Result
print("The list with binary elements is : \n" ,res)输出
运行以上代码,得到以下结果 -
The list with binary elements is : [True, True, True, True, True, True]
使用 * 运算符
* 运算符可以重复相同的值所需次数。我们使用它创建一个具有布尔值列表。
示例
res = [False] * 6
# Result
print("The list with binary elements is : \n" ,res)输出
运行以上代码,得到以下结果 -
The list with binary elements is : [False, False, False, False, False, False]
使用字节数组
我们还可以使用 byte 数组函数,它将为我们提供 0 作为默认值。
示例
res = list(bytearray(5))
# Result
print("The list with binary elements is : \n" ,res)输出
运行以上代码,得到以下结果 -
The list with binary elements is : [0, 0, 0, 0, 0]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP