有没有一种方法可以循环处理具有相似名称的字典中的文件? [英] Is there a way to work with files from a dictionary with similar names in a loop?

查看:40
本文介绍了有没有一种方法可以循环处理具有相似名称的字典中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想知道是否可以在循环中使用字典中名称相似的文件

So, I was wondering if there could be a way to use files from a dictionary with similar names in a loop,

我有这个字典:

dcm = {}
for filename in os.listdir('./GMATfiles'):
    if fnmatch.fnmatch(filename,'DCM_hydra*.txt'):
       dcm[filename[:11]] = os.path.normpath(''.join(['./GMATfiles', '/', filename]))
       #print(dcm)

#OUT_INPUT
out={}
for filename in os.listdir('./GMATfiles'):
    if fnmatch.fnmatch(filename,'Out_hydra*.txt'):
       out[filename[:11]] = os.path.normpath(''.join(['./GMATfiles', '/', filename]))
       #print(out) 
#MATRIX_INPUT 
mtr={}
for filename in os.listdir('./GMATfiles'):
    if fnmatch.fnmatch(filename,'matrizr_hydra*.txt'):
       mtr[filename[:15]] = os.path.normpath(''.join(['./GMATfiles', '/', filename]))
       #print(mtr)

我从这些词典中的每一个那里得到的名字都是一样的,除了一个数字(例如: DCM_hydra01,DCM_hydra02,DCM_hydra03 等)

The names I get from each one of these dictionaries are the same except for a number (for example:DCM_hydra01, DCM_hydra02, DCM_hydra03 etc.)

然后我需要在某些功能中使用字典中的这些文件:

Then I need to use these files from the dictionaries in some functions:

IFOV1= gi.IFOV_generic(out['Out_hydra01'],mtr['matrizr_hydra01'], dcm['DCM_hydra01'],endpoint)
IFOV2= gi.IFOV_generic(out['Out_hydra02'],mtr['matrizr_hydra02'], dcm['DCM_hydra02'],endpoint)
.
.
.

是否有一种编写循环的方法,可以让我获得这些 IFOV 函数,而无需一个接一个地编写它们?

Is there a way to write a loop that would let me get these IFOV functions without the need of writing them one by one?

推荐答案

您可以尝试使用 zip()函数(如下面的示例)对字典进行迭代.它为您列出了所有文件的所有功能.但是不要忘记,所有格言中的len应该相等

You can try iterate over dicts by zip() function like example bellow. It gives you list with all functions for all files. But don't forget than len of all dicts should be equals

dcm = {'f1': 'path_to_file'}
out = {'f1': 'path_to_file'}
mtr = {'f1': 'path_to_file'}

IFOV = []

for d, o, m in zip(dcm, out, mtr):
    IFOV.append(
        gi.IFOV_generic(out[o], mtr[m], dcm[d], endpoint)
    )

这篇关于有没有一种方法可以循环处理具有相似名称的字典中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆