2

I'm trying to count the number of unique strings in the second value of a multidimensional array.

My current code is:

>>> a=[['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']]
>>> from collections import Counter
>>> result=Counter(a[1]);
>>> result
Counter({'2a': 1, '2b': 1, '2c': 1})

But, I want the output to be this:

Counter({'1b': 1, '2b': 1, '3b': 1})

Counting the second value in each list, rather than the three values from the second list.

I realize that Counter(a[1]) is wrong, but I'm not sure how to do it the way I want.

2 Answers 2

3

To count in the second "column", try this:

a = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']]
from collections import Counter
result = Counter(zip(*a)[1])
print result

Output:

Counter({'3b': 1, '1b': 1, '2b': 1})
Sign up to request clarification or add additional context in comments.

Comments

0

Should be a bit quicker than using zip:

from collections import Counter

a = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']]
result = Counter(lst[1] for lst in a)
print(result)

gives

Counter({'3b': 1, '1b': 1, '2b': 1})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.