简体   繁体   English

连续计算出现次数

[英]Counting number of occurrences in a row

If a have a list of n booleans, what would be the best way to find how many times true appears in a list once in a row, two times in a row and so on? 如果a具有n个布尔值的列表,那么查找列表中连续出现一次,两次连续出现等等的真实次数的最佳方法是什么?

For an example: list1 = [True,False,True, True, False, False, False, True,True] 例如:list1 = [True,False,True,True,False,False,False,True,True]

true appears once in row once, and two times in a row twice. true连续出现一次,连续两次出现两次。

You can use itertools.groupby to find consecutive occurrences of Trues and collections.Counter . 您可以使用itertools.groupby查找Truescollections.Counter连续出现。

Lets try with the following list: 让我们尝试以下列表:

from itertools import groupby
from collections import Counter

l = [True, False, True, True, True, True, False, True]
Counter(sum(v) for k,v in groupby(l) if k)
# Counter({1: 2, 4: 1})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM