0

I have string value as:

s = 'asdabbdasfababbabb'

I've split the str by using below code, than get result as below :

n = 3
split_strings = [s[index : index + n] for index in range(0, len(s), n)]
['asd', 'abb', 'das', 'fab', 'abb', 'abb']

What I need to achieve:

I want to count duplicated value consiering the sequence such as :

({'asd': 1, 'abb': 1, 'das': 1, 'fab': 1, 'abb' : 2})

However, if I use Counter() it counts the duplicated value but, does not seems to consider the sequence of list:

Counter({'asd': 1, 'abb': 3, 'das': 1, 'fab': 1})

How can I achieve what I need?

asked Apr 27, 2022 at 4:56
1
  • Did you know that a dictionary cannot store two identical keys? Commented Apr 27, 2022 at 4:58

2 Answers 2

2

You cannot store duplicate keys in a dict. If you are willing to have a list of tuples, you can use itertools.groupby:

from itertools import groupby
lst = ['asd', 'abb', 'das', 'fab', 'abb', 'abb']
counts = [(k, len([*g])) for k, g in groupby(lst)]
print(counts) # [('asd', 1), ('abb', 1), ('das', 1), ('fab', 1), ('abb', 2)]
answered Apr 27, 2022 at 4:59
Sign up to request clarification or add additional context in comments.

Comments

0

The itertools.groupby function is a favorite, but perhaps future readers might appreciate an algorithm for actually finding these groupings:

def groups(*items):
 i = 0
 groups = []
 while i < len(items):
 item = items[i]
 j = i + 1
 count = 1
 while j < len(items):
 if items[j] == item:
 count += 1
 j += 1
 else:
 break
 i = j
 groups.append((item, count))
 return groups
answered Apr 27, 2022 at 5:38

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.