我在阅读字符串列表,其中每个字符串都与文件名有关。但是,每个字符串都是负号。我想出了下面的代码:如何使用re搜索Python中另一个列表中的一个列表中的项目
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 2009-12-09 07:31:25
@我会说列表中会有数千个文件。该列表应该比目录中的实际文件数量稍大(5%左右)。 – Alex 2009-12-09 22:09:34