在Python中的二进制列表中获取True值的索引
当Python列表包含true或false以及0或1之类的值时,称为二进制列表。在本文中,我们将获取一个二进制列表,并找出list元素为true的位置的索引。
用枚举
枚举函数提取列表中的所有元素。我们应用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,我们遍历列表中的每个元素。这仅显示出值为真的元素。
示例
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]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下