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?
In the above example, we have used the count() method to count the number of lists and tuples inside the tuple random . The tuple ('a', 'b') appears twice and the list [3, 4] appears once. Hence, its count in the tuple is 2 and 1 respectively.
The count() method returns the number of times a specified value appears in the tuple.
The tuples are checked for being identical using the '==' operator. This is assigned to a value. It is displayed on the console.
Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
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
Using collections.Counter
with operator.itemgetter
:
from collections import Counter
from operator import itemgetter
res = Counter(map(itemgetter(0, 2), z))
print(res)
Counter({(1, 2015): 4,
(1, 2016): 5,
(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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With