0

I have a list of strings called my_strings. I want to pull out all strings within that list that contain search_string

My attempt is the following:

new_strings = [my_str for my_str in my_strings if search_string in my_str]

I am getting the following error

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

But I don't understand why because I am just comparing two strings. If I manually pull out a random element in my terminal and do the comparison myself it works fine.

sedavidw
  • 11,116
  • 13
  • 61
  • 95
  • 3
    You have a `numpy` array somewhere, not standard Python types. – Martijn Pieters Oct 03 '14 at 16:03
  • 1
    You'll need to give us your *inputs* to reproduce the problem in more detail, but you won't see the error if `my_strings` is a standard `list` object with standard `str` elements and `search_string` being a standard `str` object too. – Martijn Pieters Oct 03 '14 at 16:06
  • You were right, didn't carefully look at the type of `my_strings`. If you write up the answer you'll get the check. Thanks! – sedavidw Oct 03 '14 at 16:11

2 Answers2

1

You have a numpy array somewhere, not standard Python types; see ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() for an example with explanation as to why numpy arrays throw this exception.

Given a basic Python list object containing standard string values, and search_string being a string too, your code just works:

>>> search_string = 'foo'
>>> my_strings = ["Let's foo the bar", 'There is spam in my egg salad', 'You are barred from entering the foodchain!']
>>> [my_str for my_str in my_strings if search_string in my_str]
["Let's foo the bar", 'You are barred from entering the foodchain!']
Community
  • 1
  • 1
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

As the error message indicates:-

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

It means your code contains numpy array then you need to compare like that below :-

>>> v = np.array([1,2,3]) == np.array([1,2,4])
>>> v
array([ True,  True, False], dtype=bool)
>>> v.any()
True
>>> v.all()
False

For more details refer this

Community
  • 1
  • 1
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56