Search code examples
pythonlistfrequency

How to count elements on each position in lists


I have a lot of lists like:

SI821lzc1n4
MCap1kr01lv

All of them have the same length. I need to count how many times each symbol appears on each position. Example:

abcd
a5c1
b51d

Here it'll be a5cd


Solution

  • One way is to use zip to associate characters in the same position. We can then send all of the characters from each position to a Counter, then use Counter.most_common to get the most common character

    from collections import Counter
    
    l = ['abcd', 'a5c1', 'b51d']
    
    print(''.join([Counter(z).most_common(1)[0][0] for z in zip(*l)]))
    # a5cd