列表的“LIKE”功能

时间:2011-07-12 04:50:04

标签: python

列表是否有任何等效的'LIKE'函数(如MySQL中)。例如;

这是我的清单:

abc = ['one', 'two', 'three', 'twenty one']

如果我提供"on"这个词,它应该打印列表中的匹配词(在这种情况下:'one''twenty one'),如果我给"fo",它应该打印False

4 个答案:

答案 0 :(得分:10)

您可以使用列表理解:

[m for m in abc if 'on' in m]

这大致转换为“对于abc中的每个元素,如果元素包含子字符串'on',则将元素附加到列表中”

答案 1 :(得分:3)

>>> abc = ['one', 'two', 'three', 'twenty one']
>>> print [word for word in abc if 'on' in word]
['one', 'twenty one']

答案 2 :(得分:3)

这些list comprehensions会满足吗?

>>> 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]
[]

你可以将它包装在一个函数中:

>>> 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
>>>

答案 3 :(得分:-1)

for x in abc:
    if "on" in x:
        print x

或者,作为一种功能,

def like(str, search):
    res = []
    for x in search:
       if str in x:
           res.append(x)
    return res