我有一个字符串列表,如果列表中的字符串出现在文件名中,那么我希望 python 打开该文件。问题是,我希望 python 按照字符串在列表中出现的顺序打开文件。我当前的代码按照 python 想要的顺序打开文件,并且仅检查列表中的字符串是否出现在文件名中。
文件
dogs.html
cats.html
fish.html
python
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:
关于python 通过字符串匹配迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12043365/