[英]How to iterate through Tuple<List<String>> in Python
[英]python iterate through list by string matching
我有一个字符串列表,如果我的列表中的字符串出现在文件名中,那么我希望python打开该文件。 问题是,我希望python按照字符串出现在我的列表中的顺序打开文件。 我当前的代码按照python想要的顺序打开文件,只检查列表中的字符串是否出现在文件名中。
档
dogs.html
cats.html
fish.html
蟒蛇
list = ['fi', 'do', 'ca']
for name in glob.glob('*.html'):
for item in list:
if item in name:
with open(name) as k:
lis = ['fi', 'do', 'ca']
for item in lis:
for name in glob.glob('*.html'):
if item in name:
with open(name) as k:
或者首先创建所有文件的列表,然后在列表的每次迭代中过滤该list
:
>>> names=glob.glob('*.html')
>>> lis=['fi','do','ca']
>>> for item in lis:
... for name in filter(lambda x:item in x,names):
... with open('name') as k:
您可以创建一组匹配项:
matching_glob = set([name for name in glob.glob('*.html')])
然后过滤您的列表
list_matching_glob = filter (lambda el: el in matching_glob) filter
你可以通过重复glob调用来做到这一点:
names = ['fi', 'do', 'ca']
patterns = [s + "*.html" for s in names]
for pattern in patterns:
for fn in glob.glob(pattern):
with open(name) as k:
pass
您可以使用os.listdir和glob.fnmatch来分解重复的文件系统访问,以防您处理数千个文件。
我会做这样的事情:
filenames = glob.glob('*.html')
for my_string in my_strings:
for fname in (filename for filename in filenames if my_string in filename):
with open(fname) as fobj:
#do something.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.