📜  Python|连续布尔范围

📅  最后修改于: 2022-05-13 01:55:44.923000             🧑  作者: Mango

Python|连续布尔范围

有时,我们会遇到一个问题,其中我们在一个列表中以 True 和 False 值的形式存在大量数据,这种问题在机器学习领域很常见,有时我们需要知道在特定位置哪个布尔值存在价值。让我们讨论一些可以做到这一点的方法。

方法 #1:使用enumerate() + zip() + list comprehension
通过使用以上三个功能的组合,这个任务可以很容易地完成。 enumerate函数处理迭代的作用, zip函数对类似的值进行分组,逻辑部分由列表理解处理。

# Python3 code to demonstrate
# Contiguous Boolean Ranging
# using enumerate() + zip() + list comprehension
  
# initializing list 
test_list = [True, True, False, False, True,
             True, True, True, False, True]
  
# printing the original list 
print ("The original list is : " + str(test_list))
  
# using enumerate() + zip() + list comprehension
# for Contiguous Boolean Ranging
res = [x for x, (i , j) in enumerate(zip( [2]
        + test_list, test_list + [2])) if i != j]
  
# printing result
print ("The boolean range list is : " + str(res))
输出:


方法 #2 : 使用sum() + accumulate() + groupby()
上述三个函数也可以组合在一起来实现特定任务,因为它们使用迭代器来实现它。 sum函数对每个值进行计数,groupby 将每个组和所有组一起由累加函数累加。

# Python3 code to demonstrate
# Contiguous Boolean Ranging
# using sum() + accumulate() + groupby()
from itertools import accumulate, groupby
   
# initializing list 
test_list = [True, True, False, False, False,
              True, True, True, False, False]
  
# printing the original list 
print ("The original list is : " + str(test_list))
  
# using sum() + accumulate() + groupby()
# for Contiguous Boolean Ranging
res = [0] + list(accumulate(sum(1 for i in j) 
              for i, j in groupby(test_list)))
  
# printing result
print ("The boolean range list is : " + str(res))
输出: