2013-03-22 144 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

相关问题