最好的答案当然是
print 'yay' if any(c in '0123456789' for c in var) else ':('
任何人都会很容易理解为什么
编辑 1
不,这不是最佳答案,因为它是以下方法中最慢的一种。
我喜欢正则表达式,但我无法想象使用正则表达式的解决方案会是最快的。
即使使用 set() 也更快。
var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man.
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 23, 1564.'''
from time import clock
import re
n = 1000
te = clock()
for i in xrange(n):
b = any(c in ('0123456789') for c in var)
print clock()-te
ss = set('0123456789')
te = clock()
for i in xrange(n):
b = ss.intersection(var)
print clock()-te
te = clock()
for i in xrange(n):
b = re.search('\d',var)
print clock()-te
regx = re.compile('\d')
te = clock()
for i in xrange(n):
b = regx.search(var)
print clock()-te
结果
0.157774521622
0.0335822010898
0.0178648403638
0.00936152499829
编辑 2
天哪!
事实上, shesei的答案是最好的答案。
和我想象的相反!
from time import clock
import re
n = 1000
te = clock()
for i in xrange(n):
b = any(dig in var for dig in '0123456789')
print clock()-te
结果
0.00467852757823
我得出结论,对var by的探索for dig in var
真的是超级超快。
我只知道它非常快。
编辑 3
没有人指出 shesei 解决方案的执行时间取决于分析字符串的内容:
from time import clock
n = 1000
var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man.
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 00, 0000.'''
te = clock()
for i in xrange(n):
b = any(dig in var for dig in '0123456789')
print clock()-te
var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man.
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 99, 9999.'''
te = clock()
for i in xrange(n):
b = any(dig in var for dig in '0123456789')
print clock()-te
给出结果
0.0035278226702
0.0132472143806
在最坏的情况下,使用 0.00936152499829 秒的编译正则表达式似乎比 shesei 的解决方案更快。但实际上,如果将编译正则表达式的时间包括在时间测量中,那么真正执行的时间是0.0216940979929秒。
那么 shesei 的解决方案仍然是最快的方法。