我試圖解析包含屬性及其值的巨大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)
任何幫助將非常感謝!
當有重複的鍵*和*值時會發生什麼?說'['a = 7','a = 7']'?是否應該合併爲[['a = 7,7']'?訂單應該保存嗎? – 2013-03-22 16:46:17
技術上這不會發生。但是,如果這樣做,重複可以被忽略。順序很重要,應該保留。 – user2199889 2013-03-22 17:14:09