同时在两个单独的dict上执行代码块

2024-06-16 08:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有这段代码,我想在两个不同的字典上执行它。我怎么能不写两次代码就轻松地做到这一点呢?我想我可以定义一个小函数,然后将每个dict传递给它。有没有更好的办法?你知道吗

    for key, value in self.mfiles.iteritems():
        if key not in self.INPUT['extras']:
            self.mfiles[key] = self.dirs['confdir'] + '/' + value

    for key, value in self.nmfiles.iteritems():
        if key not in self.INPUT['extras']:
            self.nmfiles[key] = self.dirs['confdir'] + '/' + value

Tags: key代码inselfextrasforinputif
3条回答

制作一个使用字典作为参数的方法

class MyClass:
    def doit(self, dictionary):
        for key, value in dictionary.iteritems():
        if key not in self.INPUT['extras']:
            dictionary[key] = self.dirs['confdir'] + '/' + value
    def run(self):
        self.doit(self.mfiles)
        self.doit(self.nmfiles)

我会将代码分解为另一个函数,并在所有要变异的字典上运行map(在iterable中的所有项上运行函数):

def doSomething(self, dic):
    for key, value in dic.iteritems():
        if key not in self.INPUT['extras']:
            dic[key] = self.dirs['confdir'] + '/' + value

def runMe(self):
       map(doSomething, [self.mfiles, self.nmfiles])

您可以这样做:

for data in (self.mfiles, self.nmfiles):
    for key, value in data.iteritems():
        if key not in self.INPUT['extras']:
            data[key] = self.dirs['confdir'] + '/' + value

不过,我认为编写一个小函数可能更清晰。你知道吗

相关问题 更多 >