Reputation: 151
Basically I have a long list of tuples with author names and a year like here below
a =[('Volozhyn AI', 2007),
('Lam KL', 2010),
('Boudreau NG', 2006),
('Tsuchitani M', 1997),
('Zheng LP', 1997),
The list is much longer, I need to count the times a year occurs in this list, so as output list
b = [(1970, x times),
(1971, y times), etc
I found that the function Counter counts all the elements in a list and gives a output like that. However, I can't seem to let Counter only count the years. So I have to either make a new list with only the years or another methode. Suggestions?
Upvotes: 0
Views: 130
Reputation: 8386
from collections import Counter
a =[('Volozhyn AI', 2007),
('Lam KL', 2010),
('Boudreau NG', 2006),
('Tsuchitani M', 1997),
('Zheng LP', 1997)]
b = (Counter(i[1] for i in a)).items()
print b
Output:
[(2010, 1), (1997, 2), (2006, 1), (2007, 1)]
With i[1] for i in a
you get the list with only the years ([2007, 2010, 2006, 1997, 1997]
). Then, you count them using Counter
and convert it to a list to fit your desired output.
Upvotes: 3
Reputation: 524
from collections import Counter
Counter(elem[1] for elem in a)
Will give
Counter({1997: 2, 2010: 1, 2006: 1, 2007: 1})
Above code picks up the second element [index 1] in each element and then counts..
Upvotes: 0