0

I wrote the below function to return True if it detects the string 'Device' in a list

def data_filter2(inner_list):
   return any(['Device' in str(x) for x in inner_list])

is there a way to search the list for more than one string and return True it it finds either one?

I tried

def data_filter2(inner_list):
   return any(['Device' or 'Drug' in str(x) for x in inner_list])

But this did not work.

Jstuff
  • 1,266
  • 2
  • 16
  • 27

4 Answers4

1

You could use a binary operator or or and depending on what you intend, but slightly different from how you've done it:

def data_filter2(inner_list):
   return any('Device' in str(x) or 'Drug' in str(x) for x in inner_list)

You could use a generator expression, and avoid creating a new list for your check.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

What if you reverse the logic?

def data_filter2(inner_list):
   return any([str(x) in ['Device', 'Drug'] for x in inner_list])

This provides a framework that can "accept" more items to check for. Chaining or is not very pythonic to my eyes.

What is interesting to note here is the following:

alist_ = ['drugs', '123123']
astring = 'drug'


for i in range(len(alist_)):
    print(astring in alist_[i])
print('-----')

print(astring in alist_)

#prints:
#True
#False
#-----
#False

What this says is that searching for a string in a list requires the strings to be identical (case sensitive) but searching for a string in a string allows for substrings to return True as well.

Ma0
  • 15,057
  • 4
  • 35
  • 65
  • This isn't strictly the same behaviour as the OP's original – jonrsharpe Jul 12 '16 at 16:07
  • i would say that this depends on the contents of `inner_list`. Strictly speaking it is indeed different. It will not work if each element of `inner_list` is a line read from a file for example. Boils down to __sub-sets__ and __super-sets__. – Ma0 Jul 12 '16 at 16:11
  • @Ev.Kounis is there a clever way of implementing regex so I dont have to type out Drug and Drugs? – Jstuff Jul 12 '16 at 18:06
1

The solutions using any and comprenhensions are nice. Another alternative would be to use set intersection.

In [30]: bool(set(['aaa', 'foo']) & set(['foo']))
Out[30]: True

In [31]: bool(set(['aaa', 'foo']) & set(['bar']))
Out[31]: False
Diego Allen
  • 4,623
  • 5
  • 30
  • 33
  • well this is not equivalent to `in` though. But it might actually be closer to what OP wants. – Ma0 Jul 12 '16 at 16:14
0

You can do it in one line like so:

def data_filter2(inner_list):
   return any([x in y for x in ['Device', 'Drug'] for y in inner_list])
Ma0
  • 15,057
  • 4
  • 35
  • 65