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]

更新于: 2020 年 7 月 9 日

2000+ 次浏览

开启你的 职业 生涯

完成课程并获得认证

开始学习
广告
© . All rights reserved.