3

If I have a list:

a = [np.array([1,1,1]), np.array([1,1,1]), np.array([1,1,1])]

How to do something like, a.count(np.array([1,1,1])? This throws:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Is there a function similar to .count()?

3
  • you can do len(a) with return length Commented Dec 25, 2019 at 4:06
  • What you have in this example is a Python list of numpy objects. Commented Dec 25, 2019 at 4:17
  • count is using == teat, which for arrays is element-wise, resulting in the ambiguity error. Commented Dec 25, 2019 at 6:05

2 Answers 2

1

You can use np.array_equal with sum on generator:

>>> sum(np.array_equal(x, [1,1,1]) for x in a)
3
Sign up to request clarification or add additional context in comments.

Comments

1

Or map np.array_equal and apply count to the result

map(lambda x: np.array_equal(np.array([1,1,1]),x), a).count(True)

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.