我试图创建一个方法来将多个参数化配置文件部分合并为一个。通过其参数搜索和合并对象
每个部分都可以具有特定的部分参数并包含配置变量的有效负载。有几个章节的例子:
[MySection]
foo = defaultbar
[MySection|color=red|shape=circle]
foo = bar
variable = value
[MySection|shape=circle]
otherfoo = otherbar
foo = anotherbar
那些部分由以下类表示:
class Section():
# All values here are parsed from config file
name = "MySection"
# This is a section specific parameters
params = {'color': 'red',
'share': 'circle',
'weight': 'ton'}
# This is section variables payload
vars = {'foo': 'bar',
'variable': 'value'}
def merge(self, section):
"""Merges current section vars with vars of given one"""
# ...code here...
(所有参数和VAR分配在运行时,不静态分配) 第参数可有所不同,有些可能不存在。
我需要的是一个算法来选择和合并配置部分(其变量有效载荷)为一个特定的部分参数值。
例如,我有节的列表:
sections[0].params = {'color': 'blue'}
sections[1].params = {'shape': 'circle'}
sections[2].params = {'color': 'red'}
sections[3].params = {'shape': 'circle'}
sections[4].params = {'color': 'blue',
'shape': 'circle'}
sections[5].params = {'weight': 'ton'}
sections[6].params = {'color': 'blue'}
sections[7].params = {'color': 'blue',
'shape': 'circle',
'weight': 'ton'}
的选择和合并标准(在运行时确定的)是一个OrderedDict,例如:
criteria = {'color': 'blue',
'shape': 'circle',
'weight': 'ton'}
现在我需要搜索部分列表找到至少部分满足此条件的部分。具有更多参数匹配的部分必须稍后进行合并。
随着给定的标准的部分将在下面的顺序进行合并:
sections[0] + sections[6] + sections[1] + sections[3] + sections[5] +
sections[4] + sections[7]
合并的顺序是重要的,一个可能的例外为相同的参数的部分(例如,0和6,1和3) 通用算法是:
- 搜索部仅具有标准的第一参数和合并它们
- 重复步骤1中的其它参数的标准
- 搜索部分匹配的标准...... 两个参数等等...
是否有一个快速和优雅的方式来做到这一点?
'{'x'='y'}'是无效的Python语法。要指定一个字典的键值对,你需要'{'x':'y'}'。 – 2010-12-19 12:27:17
另外,字典**没有订单**,所以你不能说“合并的顺序很重要” - 无论你将它们合并到什么顺序中,所产生的“变量”将是相同。 – 2010-12-19 12:29:06
是的,我的语法不好。 “合并顺序很重要”我的意思是section.merge()调用的顺序很重要(因为在某些情况下,部分变量会被覆盖)。现在我看到'标准'必须是OrderedDict。 – RedRampage 2010-12-19 13:24:10