0

I've got a similar array:

[['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 2291], ['fuubar', 8291]]

I want to count the same values in list[i][0], without specifying what string I want to find. Examples I've found on the Internet are either about 1D arrays or with specification. If I had a 1D array that would be extremely simple:
Example 1 with specifying the value (1)

[1, 2, 3, 4, 1, 4, 1].count(1)
3

Example 2 without specyifying what to look for

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

My desired output would be similar. Given my example, I want to know how many times does 'foo' occur, 'bar' occurs, 'fuubar' occurs. But how do I do this with a 2D array?

1
  • 2
    Note that 0091 is not a valid literal anymore. It used to be a literal octal. Commented Feb 16, 2015 at 13:38

3 Answers 3

1

Use generator expression to extract the items you want to count:

>>> from collections import Counter
>>> l = [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]
>>> Counter(item[0] for item in l)
Counter({'foo': 2, 'bar': 2, 'fuubar': 1})
Sign up to request clarification or add additional context in comments.

Comments

1
Counter([z[0] for z in [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]])

Comments

1

You can unpack:

Counter(s for s, _ in l))

Or for a functional approach:

from operator import itemgetter
print(Counter(map(itemgetter(0), l)))

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.