'LIKE' function for Lists
Is there any equivalent 'LIKE'
function(like in MySQL) for lists. for example;
This is my list开发者_Python百科:
abc = ['one', 'two', 'three', 'twenty one']
if I give the word "on"
, it should print the matching words from the list (in this case: 'one'
, 'twenty one'
) and if I give "fo"
, it should print False
You can use list comprehension:
[m for m in abc if 'on' in m]
This roughly translates to "for each element in abc, append element to a list if the element contains the substring 'on'"
>>> abc = ['one', 'two', 'three', 'twenty one']
>>> print [word for word in abc if 'on' in word]
['one', 'twenty one']
Would these list comprehensions
suffice?
>>> abc = ['one', 'two', 'three', 'twenty one']
>>> [i for i in abc if 'on' in i]
['one', 'twenty one']
>>> [i for i in abc if 'fo' in i]
[]
You could wrap this in a function:
>>> def like(l, word):
... words = [i for i in abc if word in i]
... if words:
... print '\n'.join(words)
... else:
... print False
...
>>> like(abc, 'on')
one
twenty one
>>> like(abc, 'fo')
False
>>>
for x in abc:
if "on" in x:
print x
Or, as a function,
def like(str, search):
res = []
for x in search:
if str in x:
res.append(x)
return res
精彩评论