In python, How would you calculate the number of times a unique term appears in a list, however if the term is directly after, only count 1

Viewed 80
['11A/B - FPC1', 'Tool Shelf', 'Repair', 'Tool Shelf', 'Tool Shelf', 'Repair', 'Repair', 'Tool Shelf', 'Tool Shelf', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair']

Answer would be 3 here, since 'Repair' shows up twice in the list, only counting if the previous term does not equal 'Repair'.

['11A/B - FPC1', 'Tool Shelf', 'Repair', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair']

Answer would be 2 here, since 'Repair' shows up twice in the list, only counting if the previous term does not equal 'Repair'.

2 Answers

You can use itertools.groupby with collections.Counter:

import itertools as it, collections as cl
def count_unique(d):
   return cl.Counter([a for a, _ in it.groupby(d)])

vals = ['11A/B - FPC1', 'Tool Shelf', 'Repair', 'Tool Shelf', 'Tool Shelf', 'Repair', 'Repair', 'Tool Shelf', 'Tool Shelf', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair']
vals1 = ['11A/B - FPC1', 'Tool Shelf', 'Repair', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Tool Shelf', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair', 'Repair']
print(count_unique(vals)['Repair'])
print(count_unique(vals1)['Repair'])

Output:

3
2

Another solution could be using only list indexation, asking if the next element is equal to the previous one. I have built a function that receive as parameter the term and a list and return the number of times. The idea here is storing in count_list n sub-lists with the term

def count_term(term, lst):
  count_list = []
  count_apparition = 0
  for index in range(len(lst) - 1):
    if lst[index] == term:
      if lst[index] == lst[index+1]:
        count_apparition += 1
      else:
          count_list.append([term])

  if count_apparition > 0:
        count_list.append([term])

  # Using list1, count_list wil be [['Repair'], ['Repair'], ['Repair']]
  # Using list2, count_list will be [['Repair'], ['Repair']]
  return len(count_list)

print(count_term('Repair', list1))
print(count_term('Repair', list2))

Output:

3
2
Related