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.