52

我发现自己反复编写相同的代码块:

def stringInList(str, list):
    retVal = False
    for item in list:
        if str in item:
            retVal = True
    return retVal

有什么办法可以更快/用更少的代码编写这个函数?我通常在 if 语句中使用它,如下所示:

if stringInList(str, list):
    print 'string was found!'
4

1 回答 1

76

是的,使用any()

if any(s in item for item in L):
    print 'string was found!'

正如文档所提到的,这几乎等同于您的函数,但any()可以采用生成器表达式而不仅仅是字符串和列表,以及any()短路。一旦s in item为真,函数就会中断(如果您只是更改retVal = True为,您可以简单地使用您的函数执行此操作return True。请记住,函数在返回值时会中断)。


您应该避免命名字符串str和列表list。这将覆盖内置类型。

于 2013-11-01T12:51:15.970 回答