Count values of sublists

Viewed 167

Let's say I have a list of lists in Python where each element represents a day and how many products are available in a shop:

l = [
    [a, a, a, b, c],
    [a, a, b, b, c],
    [a, b, b, c, c]
]

I would like to create a summary that shows:

Day 1: a:3, b:1, c:1 
Day 2: a:2, b:2, c:1 
Day 3: a:1, b:2, c:2

I need it in a format that I can then chart the availability of products over time.

I've tried this:

from collections import Counter
    
Counter(x for sublist in l for x in sublist)

But that counts the elements up across all lists rather than returning the result for each sublist.

Thanks everyone, here's the final solution including the charting:

from collections import Counter
d = {i:Counter(sublist) for i, sublist in enumerate(l, start=1)}
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df = df.melt('index', var_name='product',  value_name='vals')
df['product'] = df['product'].map({'A': 'a', 'B': 'b','C': 'c','D': 'd'})
sns.lineplot(x="index", y="vals", hue='product', data=df)
2 Answers

Try dict comprehension:

>>> {f'Day {i}': Counter(sublist) for i, sublist in enumerate(l, start=1)}
{'Day 1': Counter({'a': 3, 'b': 1, 'c': 1}),
 'Day 2': Counter({'a': 2, 'b': 2, 'c': 1}),
 'Day 3': Counter({'a': 1, 'b': 2, 'c': 2})}

Simpler and ugly Version ofc you can change according to your need

>>> for i in l:
...     x=Counter(i)
...     print(x['a'],'a')
...     print(x['b'],'b')
...     print(x['c'],'c')

you can retrive index by enumerating the list

Related