获取 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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP