我試圖創建一個方法來將多個參數化配置文件部分合併爲一個。通過其參數搜索和合並對象
每個部分都可以具有特定的部分參數幷包含配置變量的有效負載。有幾個章節的例子:
[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