>>> l = ['this', 'is', 'a', 'regex', 'test']
>>> s = 'this is a test string'
>>> def check(elements, string):
... for element in elements:
... if element in string:
... return True
... return False
...
>>> check(l, s)
True
どうやらこの関数はany()
import time
def main():
# Making a huge list
l = ['this', 'is', 'a', 'regex', 'test'] * 10000
s = 'this is a test string'
def check(elements, string):
for element in elements:
if element in string:
return True
return False
def test_a(elements, string):
"""Testing check()"""
start = time.time()
check(elements, string)
end = time.time()
return end - start
def test_b(elements, string):
"""Testing any()"""
start = time.time()
any(element in string for element in elements)
end = time.time()
return end - start
print 'Using check(): %s' % test_a(l, s)
print 'Using any(): %s' % test_b(l, s)
if __name__ == '__main__':
main()
結果:
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 5.96046447754e-06
pearl:~ pato$ python test.py
Using check(): 1.90734863281e-06
Using any(): 7.15255737305e-06
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 6.91413879395e-06
しかし、 のように と組み合わせるany()
と、結果は次のmap()
ようになります。any(map(lambda element: element in string, elements))
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00903916358948
pearl:~ pato$ python test.py
Using check(): 2.86102294922e-06
Using any(): 0.00799989700317
pearl:~ pato$ python test.py
Using check(): 3.09944152832e-06
Using any(): 0.00829982757568