python - How to combine sub-sublists only if they share a common value? -
i have sublists filled own sublists. if sub-sublists share common value @ index 1, i'd combine 2 sublists 1 merging/combining items in sub-sublists create 1 sub-sublist.
l = [[ ['sublist1','aaa','10','apple,pear,banana'], ['sublist1','aaa','50','peach,orange,banana'], ['sublist1','ddd','3','bike,street'] ],[ ['sublist2','ccc','50','tomator,lemmon'], ['sublist2','eee','30','phone,sign'], ['sublist2','ccc','90','strawberry'], ['sublist2','fff','30','phone,sign'] ],[ ['sublist3','bbb','100','tomator,lemmon'], ['sublist3','bbb','100','pear'], ['sublist3','fff','90','strawberry'], ['sublist3','fff','50',''] ]]
for example, if sub-sublists share aaa @ index 1, combine items @ index 2 , 3. in case 10 , 50 become '10,50', , 'apple,pear,banana' , 'peach,orange,banana' become 'apple,pear,banana,peach,orange,banana'.
desired_result = [[ ['sublist1','aaa','10,50','apple,pear,banana,peach,orange'], ['sublist1','ddd','3','bike,street'] ],[ ['sublist2','ccc','50,90','tomator,lemmon,strawberry'], ['sublist2','eee','30','phone,sign'], ['sublist2','fff','30','phone,sign'] ],[ ['sublist3','bbb','100,100','tomator,lemmon,pear'], ['sublist3','fff','90,50','strawberry'] ]]
can try this?
i assumed there 'sublist2'
in front of 'fff'
in sample l
.
def merge(lst): def j(sq): return ",".join(sq) def m(sl): dic = {} ssl in sl: k = tuple(ssl[0:2]) try: v = dic[k] except keyerror: dic[k] = v = (set(), set()) v[0].update( set(ssl[2].split(',')) ) v[0].discard('') v[1].update( set(ssl[3].split(',')) ) v[1].discard('') return [ list(k) + [j(v[0])] + [j(v[1])] k, v in sorted(dic.iteritems()) ] return [ m(sl) sl in lst ] sl in merge(l): print sl
Comments
Post a Comment