Finding count of tuples with same first and third item in list of tuples

  • A+
Category:Languages

I have a list of tuples each with three items :

z = [(1, 4, 2015), (1, 11, 2015), (1, 18, 2015), (1, 25, 2015), (2, 1, 2015), (2, 8, 2015), (2, 15, 2015), (2, 22, 2015), (3, 1, 2015), (3, 8, 2015), (3, 15, 2015), (3, 22, 2015), (3, 29, 2015), (4, 5, 2015), (4, 12, 2015), (4, 19, 2015), (4, 26, 2015), (5, 3, 2015), (5, 10, 2015), (5, 17, 2015), (5, 24, 2015), (5, 31, 2015), (6, 7, 2015), (6, 14, 2015), (6, 21, 2015), (6, 28, 2015), (7, 5, 2015), (7, 12, 2015), (7, 19, 2015), (7, 26, 2015), (8, 2, 2015), (8, 9, 2015), (8, 16, 2015), (8, 23, 2015), (8, 30, 2015), (9, 6, 2015), (9, 13, 2015), (9, 20, 2015), (9, 27, 2015), (10, 4, 2015), (10, 11, 2015), (10, 18, 2015), (10, 25, 2015), (11, 1, 2015), (11, 8, 2015), (11, 15, 2015), (11, 22, 2015), (11, 29, 2015), (12, 6, 2015), (12, 13, 2015), (12, 20, 2015), (12, 27, 2015), (1, 3, 2016), (1, 10, 2016), (1, 17, 2016), (1, 24, 2016), (1, 31, 2016)] 

I want to find number of tuples in the list with same first and third items, like with first item 1 and third item 2015, there are 4 tuples; with first item 2 and third item 2015, there are 4 tuples.

I tried :

for tup in z:     a=tup[0]     b=tup[2]     print(len(set({a:b}))) 

It doesn't give desired result. How to do it?

 


using standard python's itertools.groupby:

from itertools import groupby  for grp, elmts in groupby(z, lambda x: (x[0], x[2])):     print(grp, len(list(elmts))) 

Edit:

an even nicer solution by using operator.itemgetter instead of lambda:

from operator import itemgetter from itertools import groupby  for grp, elmts in groupby(z, itemgetter(0, 2)):     print(grp, len(list(elmts))) 

Output:

(1, 2015) 4 (2, 2015) 4 (3, 2015) 5 (4, 2015) 4 (5, 2015) 5 (6, 2015) 4 (7, 2015) 4 (8, 2015) 5 (9, 2015) 4 (10, 2015) 4 (11, 2015) 5 (12, 2015) 4 (1, 2016) 5 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: