不要使用正则表达式;只需使用.endswith('/')
:
for path in lst:
if path.endswith('/'):
dir_list.append(path)
else:
file_list.append(path)
.endswith()
比正则表达式执行得更好并且更容易启动:
>>> sample = ['fileA.jpg', 'fileB.jpg', 'images/'] * 30
>>> import random
>>> random.shuffle(sample)
>>> from timeit import timeit
>>> import re
>>> def re_partition(pattern=re.compile(r'/$')):
... for e in sample:
... if pattern.search(e): pass
... else: pass
...
>>> def endswith_partition():
... for e in sample:
... if e.endswith('/'): pass
... else: pass
...
>>> timeit('f()', 'from __main__ import re_partition as f, sample', number=10000)
0.2553541660308838
>>> timeit('f()', 'from __main__ import endswith_partition as f, sample', number=10000)
0.20675897598266602