且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串是否在列表中的任何项目中包含特定字符的最快方法

更新时间:2023-11-26 08:09:40

您可以尝试通过会员资格检查来理解列表

You can try list comprehension with membership check

>>> lestring = "Text123"
>>> lelist = ["Text", "foo", "bar"]
>>> [e for e in lelist if e in lestring]
['Text']

与您的实现相比,尽管LC有一个隐式循环,但是它更快,因为没有像count

Compared to your implementation, though LC has an implicit loop but its faster as there is no explicit function call as in your case with count

与Joe的实现相比,您的实现更快,因为filter函数需要循环调用两个函数lambdacount

Compared to Joe's implementation, yours is way faster, as the filter function would require to call two functions in a loop, lambda and count

>>> def joe(lelist, lestring):
    return ''.join(random.sample(x + 'b'*len(x), len(x)))

>>> def uz(lelist, lestring):
    for x in lelist:
        if lestring.count(x):
            return 'Yep. "%s" contains characters from "%s" item.' % (lestring, x)


>>> def ab(lelist, lestring):
    return [e for e in lelist if e in lestring]

>>> t_ab = timeit.Timer("ab(lelist, lestring)", setup="from __main__ import lelist, lestring, ab")
>>> t_uz = timeit.Timer("uz(lelist, lestring)", setup="from __main__ import lelist, lestring, uz")
>>> t_joe = timeit.Timer("joe(lelist, lestring)", setup="from __main__ import lelist, lestring, joe")
>>> t_ab.timeit(100000)
0.09391469893125759
>>> t_uz.timeit(100000)
0.1528471407273173
>>> t_joe.timeit(100000)
1.4272649857800843


对于较短的字符串,Jamie的评论解决方案比较慢.这是测试结果


Jamie's commented solution is slower for shorter string's. Here is the test result

>>> def jamie(lelist, lestring):
    return next(itertools.chain((e for e in lelist if e in lestring), (None,))) is not None

>>> t_jamie = timeit.Timer("jamie(lelist, lestring)", setup="from __main__ import lelist, lestring, jamie")
>>> t_jamie.timeit(100000)
0.22237164127909637


如果需要布尔值,对于较短的字符串,只需修改上述LC表达式


If you need Boolean values, for shorter strings, just modify the above LC expression

[e in lestring for e in lelist if e in lestring]

或者对于更长的字符串,您可以执行以下操作

Or for longer strings, you can do the following

>>> next(e in lestring for e in lelist if e in lestring)
True

>>> any(e in lestring for e in lelist)