把列表o中的前三列元素(cmd,opt,xx.x(x)SE)作为key,合并第4列(Catxxxx)的元素。下面的例子是由列表o创建新的列表o_new。o = []a = ['cmd',['opt1','opt2'],'12.2(2)SE','Cat3560']b = ['cmd',['opt1','opt2'],'12.2(2)SE','Cat4500']c = ['cmd',['opt1','opt2','opt3','opt4'],'12.3(2)SE','Cat3560']d = ['cmd',['opt1','opt2','opt3'],'12.4(2)SE','Cat3560']o.append(a)o.append(b)o.append(c)o.append(d)想要的结果:o_new[0] = ['cmd',['opt1','opt2'],'12.2(2)SE',['Cat3560','Cat4500']] → 这个是由a,b合并成的o_new[1] = ['cmd',['opt1','opt2','opt3','opt4'],'12.3(2)SE','Cat3560']o_new[2] = ['cmd',['opt1','opt2','opt3'],'12.4(2)SE','Cat3560']恳请大神不吝赐教!
1 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
下面的可以实现,可能代码有点丑:
def combine_list(list1, list2): list0 = list1[:] if list1[0] == list2[0] and list1[1] == list2[1] and list1[2] == list2[2]: list_temp = [list1[3], list2[3]] list0[3] = list_temp return list0 else: passo = [] a = ['cmd', ['opt1', 'opt2'], '12.2(2)SE', 'Cat3560'] b = ['cmd', ['opt1', 'opt2'], '12.2(2)SE', 'Cat4500'] c = ['cmd', ['opt1', 'opt2', 'opt3', 'opt4'], '12.3(2)SE', 'Cat3560'] d = ['cmd', ['opt1', 'opt2', 'opt3'], '12.4(2)SE', 'Cat3560'] o.append(a) o.append(b) o.append(c) o.append(d) o_new = o[:] i = 1j = 0for i in range(i, len(o)): temp = combine_list(o[j], o[i]) if temp is not None: o_new.append(temp) o_new.remove(o[j]) o_new.remove(o[i]) if i == 3: j += 1 i = 1 if j == 3: breakprint(o_new)
Result: [['cmd', ['opt1', 'opt2', 'opt3', 'opt4'], '12.3(2)SE', 'Cat3560'], ['cmd', ['opt1', 'opt2', 'opt3'], '12.4(2)SE', 'Cat3560'], ['cmd', ['opt1', 'opt2'], '12.2(2)SE', ['Cat3560', 'Cat4500']]]
添加回答
举报
0/150
提交
取消