这是一个基准测试,显示使用str.lower http://docs.python.org/2/library/string.html?highlight=lower#string.lower比接受的答案提出的方法更快(libc.strcasecmp
):
#!/usr/bin/env python2.7
import random
import timeit
from ctypes import *
libc = CDLL('libc.dylib') # change to 'libc.so.6' on linux
with open('/usr/share/dict/words', 'r') as wordlist:
words = wordlist.read().splitlines()
random.shuffle(words)
print '%i words in list' % len(words)
setup = 'from __main__ import words, libc; gc.enable()'
stmts = [
('simple sort', 'sorted(words)'),
('sort with key=str.lower', 'sorted(words, key=str.lower)'),
('sort with cmp=libc.strcasecmp', 'sorted(words, cmp=libc.strcasecmp)'),
]
for (comment, stmt) in stmts:
t = timeit.Timer(stmt=stmt, setup=setup)
print '%s: %.2f msec/pass' % (comment, (1000*t.timeit(10)/10))
我的机器上的典型时间:
235886 words in list
simple sort: 483.59 msec/pass
sort with key=str.lower: 1064.70 msec/pass
sort with cmp=libc.strcasecmp: 5487.86 msec/pass
所以,版本str.lower
它不仅是迄今为止最快的,而且也是这里提出的所有解决方案中最可移植和Pythonic的。
我没有分析内存使用情况,但原始发布者仍然没有给出令人信服的理由来担心它。另外,谁说对 libc 模块的调用不会重复任何字符串?
NB: The lower()
字符串方法还具有与语言环境相关的优点。在编写自己的“优化”解决方案时,您可能不会得到正确的结果。即便如此,由于 Python 中的错误和缺失功能,这种比较可能会在 unicode 上下文中给出错误的结果。