Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)]

Solution 2:

The fastest way would be to use map and itemgetter:

from operator import itemgetter

l = [('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)]

cn = Counter(map(itemgetter(1), l))

print(list(cn.items()))

Solution 3:

Another way is Defaultdict-

from collections import defaultdict

dd = defaultdict(int)

d= [('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)]
for i in d:
    dd[i[1]]+=1
counts  =  [i for i in dd.iteritems()]
print counts

Prints-

[(1, 3), (2, 2), (3, 3), (4, 2), (5, 2), (6, 2), (7, 2), (8, 1), (9, 1)]

Post a Comment for "Count Occurrence Of Tuples With Python"