获取 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 次浏览

开启你的职业

学习课程,获得认证

开始
广告
© . All rights reserved.