在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]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短