我在研究算法,我有一个关于isdigit()
和my_isdigit()
之间的差异的问题.
import time
def my_isdigit(str):
s = set(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'])
for x in str:
if x not in s:
return False
return True
test_str = '1234567890' * 10000000
start = time.time()
test_str.isdigit()
print(time.time() - start) # 0.21125102043151855
start = time.time()
my_isdigit(test_str)
print(time.time() - start) # 2.169161319732666
为什么isdigit()
比我的快得多?
我看到了What is the fastest way to make sure a str is a int?个,但我不知道原因.
这是C和Python之间的区别吗?还是我的代码不好?