我正在编写程序,需要使用此函数将依赖项添加到xml文件中。这段代码有效,但我想问一下是否有更多的pythonic方法。
我认为我以非pythonic方式进行的部分是嵌套for循环。有没有更好的方法来迭代字典列表和每个值?
def add_Dependencies(self):
""" Adds the dependencies in a feature using dictionaries. When
a feature is loaded, its dependencies are added to
dictionaries. Three for each type of software that the
dependencies are categorized as."""
dependency_dict_list = [
self.os_dict, self.visual_dict, self.audio_dict
]
dependencies = self.dependencies
for dictionary in dependency_dict_list:
for feature, software in dictionary.items():
if all(dependency.text != feature for dependency in dependencies):
etree.SubElement(dependencies,"Dependency", Software = software).text = feature
答案 0 :(得分:0)
老实说,这完全没有错。我把它放在一起,如果你感兴趣它应该更快一点,并且稍微冗长一点。我剪掉了嵌套的for循环并将所有内容翻到了任何一个(它对我来说看起来更干净,但这真的只是味道)。
all_dependencies = dict(self.os_dist, **self.visual_dict)
all_dependencies.update(self.audio_dict)
for feature, software in dictionary.items():
if not any(dependency.text == feature for dependency in dependencies):
etree.SubElement(dependencies,"Dependency", Software = software).text = feature
答案 1 :(得分:0)
您可以使用collections.ChainMap
将三个词典合并为一个类似字典的映射。或者,由于您不关心值,因此可以将其键合并到set
使用它来避免嵌套循环并不是很重要。嵌套循环可以是完美的Pythonic,但如果嵌套变得太深,你可能想要将一些内部因素分解为函数。
您可能希望在此处使用ChainMap
或set
的真正原因是为了避免搜索XML树的O(N**2)
运行时复杂性,以消除重复的依赖关系。他们也消除了一定程度的嵌套,这是一个小的附带好处。
尝试这样的事情:
new_dependencies = (set(self.os_dict).union(self.visual_dict, self.audio_dict) -
set(dependency.text for dependency in self.dependencies))
for feature in new_dependencies:
etree.SubElement(self.dependencies,"Dependency", Software = software).text = feature