獲取 Python 二進位制列表中真值索引


當一個 Python 列表包含真或假,0 或 1 等值時,它被稱為二進位制列表。在本文中,我們將採用一個二進位制列表,並找出列表元素為真的位置的索引。

使用 enumerate

enumerate 函式提取列表中的所有元素。我們應用 a in 條件來檢查提取的值是否為真。

示例

 線上演示

listA = [True, False, 1, False, 0, True]
# printing original list
print("The original list is :\n ",listA)
# using enumerate()
res = [i for i, val in enumerate(listA) if val]
# printing result
print("The indices having True values:\n ",res)

輸出

執行上述程式碼會得到以下結果:

The original list is :
[True, False, 1, False, 0, True]
The indices having True values:
[0, 2, 5]

使用 compress

使用 compress,我們遍歷列表中的每個元素。這隻會呈現值為真的元素。

示例

 線上演示

from itertools import compress
listA = [True, False, 1, False, 0, True]
# printing original list
print("The original list is :\n ",listA)
# using compress()
res = list(compress(range(len(listA)), listA))
# printing result
print("The indices having True values:\n ",res)

輸出

執行上述程式碼會得到以下結果:

The original list is :
[True, False, 1, False, 0, True]
The indices having True values:
[0, 2, 5]

更新於:2020-06-04

644 次瀏覽

開啟你的職業

學習課程,獲得認證

開始
廣告