[英]return a random item in a list of matching strings from a list of strings efficiency
im writing a function to return a random file in a directory, also - i want to be able to match a substring in the file name. 我正在编写一个函数来返回一个目录中的随机文件,我希望能够匹配文件名中的子字符串。
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)
this code will work, but i am working with LOTS of files and this code takes a while, i tried doing it with list comprehension and mapping and i couldn't make it work. 这段代码可以正常工作,但我正在处理大量的文件,这段代码需要一段时间,我尝试用列表理解和映射来完成它,我无法使它工作。 any suggestions?
有什么建议么?
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])
Documentation on list comprehensions : 关于列表理解的文档:
http://docs.python.org/tutorial/datastructures.html#list-comprehensions http://docs.python.org/tutorial/datastructures.html#list-comprehensions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.