Search code examples
pythonlistcountersublist

How to count the number of times a certain pattern in a sublist occurs within a list and then append that count to the sublist?


The challenge is that I want to count the number of times a certain pattern of items occurs in a sub-list at certain indices.

For example, I'd like to count the number of times a unique patter occurs at index 0 and index 1. 'a' and 'z' occur three times below at index 0 and index 1 while '1' and '2' occur two times below at index 0 and index 1. I'm only concerned at the pair that occurs at index 0 and 1 and I'd like to know the count of unique pairs that are there and then append that count back to the sub-list.

List = [['a','z','g','g','g'],['a','z','d','d','d'],['a','z','z','z','d'],['1','2','f','f','f'],['1','2','3','f','f'],['1','1','g','g','g']]

Desired_List = [['a','z','g','g','g',3],['a','z','d','d','d',3],['a','z','z','z','d',3],['1','2','f','f','f',2],['1','2','3','f','f',2],['1','1','g','g','g',1]]

Currently, my attempt is this:

from collections import Counter
l1 = Counter(map(lambda x: (x[0] + "|" + x[1]),List)

Deduped_Original_List = map(lambda x: Counter.keys().split("|"),l1)
Counts = map(lambda x: Counter.values(),l1)

for ele_a, ele_b in zip(Deduped_Original_List, Counts):
    ele_a.append(ele_b)

This clearly doesn't work because in the process I lose index 2,3, and 4.


Solution

  • You can use list comprehension with collections.Counter:

    from collections import Counter
    lst = [['a','z','g','g','g'],['a','z','d','d','d'],['a','z','z','z','d'],['1','2','f','f','f'],['1','2','3','f','f'],['1','1','g','g','g']]
    cnt = Counter([tuple(l[:2]) for l in lst])
    lst_output = [l + [cnt[tuple(l[:2])]] for l in lst]
    print lst_output
    

    Ouput:

    [['a', 'z', 'g', 'g', 'g', 3], ['a', 'z', 'd', 'd', 'd', 3], ['a', 'z', 'z', 'z', 'd', 3], ['1', '2', 'f', 'f', 'f', 2], ['1', '2', '3', 'f', 'f', 2], ['1', '1', 'g', 'g', 'g', 1]]