2

I am trying to solve the following problem:

I have a python list with multiple different elements and each of them can be repeated:

list =  ['a', 'a', 'b', 'a', 'foo','foo','foo', 'c','foo', 'd', 'foo','foo']

And I want to know how many times a certain element, e.g. foo appears n times in a row, without counting the first appearance. Thus, the counting of list would go as follows:

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

The desired output would be 3 in this case.

Is there any clean way to do it?

I saw this, but this is for a specific number of appearances. In my case the number of appearances in a row is not predetermined. I think I neither could use this other for the same reason.

KevinYanesG
  • 171
  • 1
  • 6

4 Answers4

2

via 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
Nk03
  • 14,699
  • 2
  • 8
  • 22
  • TIL there is a groupby method – Arpit Choudhary May 07 '21 at 12:15
  • Thanks! This is exactly what I was looking for. Just one quick note: If anyone is facing a similar problem but with a list of lists, you can do two approaches: Either filter the nested list to a simple list with a comprehension. Or directly change the `groupby` like in [this answer](https://stackoverflow.com/a/57594884/15450772). – KevinYanesG May 07 '21 at 14:13
0
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'))
Arpit Choudhary
  • 98
  • 1
  • 10
0
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'))

Matteo Zanoni
  • 3,429
  • 9
  • 27
0

You can do it like so:

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
Ma0
  • 15,057
  • 4
  • 35
  • 65