Search code examples
pythondictionarycollectionscounter

How can I make a dictionary / collections.counter that takesz into account the index in Python?


I am aware of dictionaries and collection.Counters in Python. My question is how can I make one that takes index of the string into account? For example for this string: aaabaaa I would like to make a tuples that contain each string in progression, keeping track of the count going left to right and resetting the count once a new alphanumeric is found. For example, I like to see this output: [('a', 3), ('b', 1), ('a', 3)]

Any idea how to use the dictionary / Counter/ or is there some other data structure built into Python I can use?

Regards


Solution

  • You could use groupby:

    from itertools import groupby
    
    m = [(k, sum(1 for _ in v)) for k, v in groupby('aaabaaa')]
    
    print(m)
    

    Output

    [('a', 3), ('b', 1), ('a', 3)]
    

    Explanation

    The groupby function makes an iterator that returns consecutive keys and groups from the iterable, in this case 'aaabaaa'. The key k is the value identifying of the group, ['a', 'b', 'a']. The sum(1 for _ in v) count the amount of elements in the group.