2013-03-22 145 views
-2

我試圖解析包含屬性及其值的巨大Excel文件。 問題如下:某些屬性能夠包含多個值。在列表中收集部分重複元素並將它們合併到一個元素中

實施例:

list = ['a=1', 'b=2', 'c=3', 'd=4', 'd=5', 'd=6', 'e=7'] 

應該是:

list2 = ['a=1', 'b=2', 'c=3', 'd=4,5,6', 'e=7'] 

的元素是具有可變長度的字符串,並且它們通過一個 '=' 分隔。

我這是怎麼生成列表出來的Excel文件:

#for each row in the excel file. 
for rows in range(DATA_ROW, sheet.nrows): 
#generate a list with all properties. 
for cols in range(sheet.ncols): 
    #if the propertie is not emty 
    if str(sheet.cell(PROPERTIE_ROW,cols).value) is not '': 
     proplist.append(sheet.cell(PROPERTIE_ROW,cols).value + '=' + str(sheet.cell(rows,cols).value) + '\n') 

我給它一個嘗試,但沒有很好地工作......

last_item = '' 
new_list = [] 
#find and collect multiple values. 
for i, item in enumerate(proplist): 
#if the propertie is already in the list 
if str(item).find(last_item) is not -1: 
    #just copy the value and append it to the propertie 
    new_list.insert(i, propertie); 
else: 
    #slize the string in propertie and value 
    pos = item.find('=') 
    propertie = item[0:pos+1] 
    value = item[pos+1:len(item)] 
    #save the propertie 
    last_item = propertie 
    #append item 
    new_list.append(item) 

任何幫助將非常感謝!

+0

當有重複的鍵*和*值時會發生什麼?說'['a = 7','a = 7']'?是否應該合併爲[['a = 7,7']'?訂單應該保存嗎? – 2013-03-22 16:46:17

+0

技術上這不會發生。但是,如果這樣做,重複可以被忽略。順序很重要,應該保留。 – user2199889 2013-03-22 17:14:09

回答

1

如果順序並不重要,你很可能使用defaultdict對於這樣的事情:

from collections import defaultdict 
orig = ['a=1', 'b=2', 'c=3', 'd=4', 'd=5', 'd=6', 'e=7'] 
d = defaultdict(list) 
for item in orig: 
    k,v = item.split('=',1) 
    d[k].append(v) 

new = ['{0}={1}'.format(k,','.join(v)) for k,v in d.items()] 
print(new) #['a=1', 'c=3', 'b=2', 'e=7', 'd=4,5,6'] 

我想,如果爲了此事做,你可以使用一個OrderedDict + setdefault但它真的不是很漂亮:

from collections import OrderedDict 
orig = ['a=1', 'b=2', 'c=3', 'd=4', 'd=5', 'd=6', 'e=7'] 
d = OrderedDict() 
for item in orig: 
    k,v = item.split('=',1) 
    d.setdefault(k,[]).append(v) 

new = ['{0}={1}'.format(k,','.join(v)) for k,v in d.items()] 
print new # ['a=1', 'b=2', 'c=3', 'd=4,5,6', 'e=7'] 
+0

我不知道這是否是一個好主意,但我創建了一個OrderedDefaultDict,如下所示:'__init__'定義爲'class OrderedDefaultDict(OrderedDict,defaultdict):'def __init __(self,default): defaultdict .__ init __自我,默認); OrderedDict .__ init __(self)'。它似乎工作,但我沒有多重繼承的經驗。我只是交叉手指,希望'OrderedDict'和'defaultdict'覆蓋'dict'的不同方法。但我認爲我至少會提到這個想法。 – 2013-03-22 17:14:23

+0

@StevenRumbalski - 我之前也曾這樣做過。但實際上,只需將'OrderedDict'子類並將「默認」行爲放入'__missing__'中可能更容易。 – mgilson 2013-03-22 17:23:16

相關問題