Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count occurrence of tuples with Python

I'm trying to convert a list of Python tuples that display product and cost to a list of tuples that display the cost and the count of products at a given cost.

For example, given the below input:

[('Product1', 9), ('Product2', 1),
 ('Product3', 1), ('Product4', 2),
 ('Product5', 3), ('Product6', 4),
 ('Product7', 5), ('Product8', 6), 
 ('Product9', 7), ('Product10', 8), 
 ('Product11', 3), ('Product12', 1), 
 ('Product13', 2), ('Product14', 3), 
 ('Product15', 4), ('Product16', 5), 
 ('Product17', 6), ('Product18', 7)]

I'm trying to create a function in Python that would render the below. i.e. The value 1 is rendered 3 times for three different products, hence (1, 3).

[(1, 3), (2, 1), (3, 2), (4, 1), (5, 2), (6, 2), (7, 2), (8, 1) (9, 1)]
like image 814
sokeefe Avatar asked Dec 19 '25 17:12

sokeefe


1 Answers

Maybe collections.Counter could solve your problem:

>>> from collections import Counter
>>> c = Counter(elem[1] for elem in given_list)

Output will look like this:

Counter({1: 3, 3: 3, 2: 2, 4: 2, 5: 2, 6: 2, 7: 2, 8: 1, 9: 1})

If you want it in a list like you've specified in the question, then you can do this:

>>> list(c.iteritems())
[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]
like image 152
JRodDynamite Avatar answered Dec 22 '25 08:12

JRodDynamite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!