Reputation: 3635
I have some data, for example:
input=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U1'], ['2', '9', 'U1'], ['2.5', '6.5', 'U1'], ['2.5', '8', 'U1'], ['2.5', '10', 'U2'], ['3', '4.5', 'U2'], ['3', '9', 'U2'], ['3.5', '5.5', 'U2']]
How can I get numbers of how many U1 and U2 data is in all my data? This U1 and U2 is always on last place of every row, but has various name(so it must first read name....)!!!. I want to get for this example:
U1: 6
U2: 4
Upvotes: 0
Views: 135
Reputation: 304345
For python2.7+
>>> from operator import itemgetter
>>> from collections import Counter
>>> Counter(map(itemgetter(-1), input))
Counter({'U1': 6, 'U2': 4})
Using input
as a variable name is a bad idea because it shadows the builtin input()
Upvotes: 3
Reputation: 56058
I modified the index from 2
to -1
to reflect your requirement of 'last element on every row' in case each row has a different number of elements.
from collections import defaultdict
d = defaultdict(int)
for record in input:
d[record[-1]] += 1
print d
Upvotes: 6
Reputation: 993791
You can do this using a list comprehension:
num_u1 = len([x for x in input if x[2] == "U1"])
num_u2 = len([x for x in input if x[2] == "U2"])
There are other ways to do this that are less repetitive if you have more than two things you're looking for.
Upvotes: 4