[英]Count how many times an element appears n times in a row within a python list
我正在尝试解决以下问题:
我有一个包含多个不同元素的 python list
,每个元素都可以重复:
list = ['a', 'a', 'b', 'a', 'foo','foo','foo', 'c','foo', 'd', 'foo','foo']
我想知道某个元素有多少次,例如foo
连续出现 n 次,不计算第一次出现。 因此, list
的计数将 go 如下:
list = ['a', 'a', 'b', 'a', 'foo','foo','foo', 'c','foo', 'd', 'foo','foo']
+0, +0 , +0 , +0 ,+0 , +1 , +1 , +0 , +0 , +0 , +0 , +1 = 3
在这种情况下,所需的 output 将为3
。
有什么干净的方法吗?
我看到了这个,但这是针对特定数量的出场。 在我的情况下,连续出现的次数不是预先确定的。 我想我也不能出于同样的原因使用这个。
通过 groupby
from itertools import groupby
l = ['a', 'a', 'b', 'a', 'foo', 'foo', 'foo', 'c', 'foo', 'd', 'foo', 'foo']
result = sum(len(list(key))-1 for grp, key in groupby(l)
if grp == 'foo') # prints 3
lis = ['a', 'a', 'b', 'a', 'foo', 'foo', 'foo', 'c', 'foo', 'd', 'foo', 'foo']
def count_occurence(desired):
count = 0
last_item = None
for item in lis:
if item == desired:
if last_item == desired:
continue
count += 1
last_item = item
return count
print(count_occurence('foo'))
def count_function(list, target): if len(list) < 2: return 0 val = 0 prev = list[0] for elem in list[1:]: if elem == target and elem == prev: val += 1 prev = elem return val list = ['a', 'a', 'b', 'a', 'foo','foo','foo', 'c','foo', 'd', 'foo','foo'] print(count_function(list, 'foo'))
你可以这样做:
def special_count(l, n):
from collections import Counter
from itertools import groupby
s = 0
for k, v in groupby(lst):
if k == n:
s += sum(1 for _ in v) - 1
return s
lst = ['a', 'a', 'b', 'a', 'foo', 'foo', 'foo', 'c', 'foo', 'd', 'foo', 'foo']
print(special_count(lst, 'foo')) #_> 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.