从字符串效率列表中返回匹配字符串列表中的随机项

时间:2012-08-02 08:32:43

标签: python list random string-matching

即时编写一个函数来返回目录中的随机文件,我希望能够匹配文件名中的子字符串。

def get_rand_file(folder, match=None):
    if match == None:
        return random.choice(os.listdir(folder))
    else:
        matching = []
        for s in os.listdir(folder):
            if match in s:
                matching.append(s)
        return random.choice(matching)

这段代码可行,但我正在处理很多文件,这段代码需要一段时间,我尝试使用列表理解和映射,我无法使其工作。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

def get_rand_file(folder, match=None):
   if match == None:
       return random.choice(os.listdir(folder))
   else:
       return random.choice([s for s in os.listdir(folder) if match in s])

关于列表理解的文档:

http://docs.python.org/tutorial/datastructures.html#list-comprehensions