【发布时间】:2009-12-09 06:38:55
【问题描述】:
我正在阅读一个字符串列表,每个字符串都与一个文件名相关。但是,每个字符串都减去扩展名。我想出了以下代码:
import re
item_list = ['item1', 'item2']
search_list = ['item1.exe', 'item2.pdf']
matches = []
for item in item_list:
# Match item in search_list using re - I assume this is the best way to do this
regex = re.compile("^"+item+"\.")
for file in search_list:
if regex.match(file):
matches.append((item, file))
至于重复匹配,我并不担心两个文件被命名为“foo.bar”和“foo.foo.bar”。话虽如此,有没有更好的方法呢?
谢谢。
【问题讨论】:
-
有助于了解两个列表各有多少项,以及调用代码的频率。
-
@Will,我会说列表中有数千个文件。该列表应该比目录中的实际文件数略大(5% 左右)。