Python : Iterate through list and sublists and match first elements and do some more manipulations -
i new python, want know if there built in function or other way below in python 2.7:
iterate through list , sublists , if value of first element matches value of first sublist element, delete first sublist element , put other elements in sublist in outside list. sublists. see below examples better understanding of requirement.
examples:
input : ['or', ['or', 'r', '-b'], 'w'] output : ['or', 'r', '-b', 'w']
here, 'or' , 'or' matched in main list , sublist, remove 'or' in sublist , put other elements in sublist 'r' , '-b' in main list
input : ['and', ['and', ['or', '-p', 'r'], ['or', 'q', 'r']], ['or', '-p', '-r']] output : ['and', ['or', '-p', 'r'], ['or', 'q', 'r'], ['or', '-p', '-r']]
here, 'and' , 'and' matched in main list , sublist
input : ['and', ['and', ['or', 'a', 'c'], ['or', 'a', 'd']], ['and', ['or', 'b', 'c'], ['or', 'b', 'd']]] output : ['and', ['or', 'a', 'c'], ['or', 'a', 'd'], ['or', 'b', 'c'], ['or', 'b', 'd']]
here, 'and' , 'and' matched in main list , sublist1, remove 'and' in sublist1 , put other elements in sublist1 in main list. 'and' , 'and' matched in main list , sublist2, remove 'and' in sublist2 , put other elements in sublist2 in main list.
hope explained questions examples
thanks!
these 2 work: 1 recursively, 1 not. however, only work lists, annoying. if switch checking iterables, they'll eat strings. i'll figure out fix in moment.
def condense(l): outp = [l[0]] x in l[1:]: if isinstance(x,list) , x[0]==l[0]: outp += x[1:] else: outp.append(x) return outp def condense_r(l): outp = [l[0]] x in l[1:]: if isinstance(x,list): z = condense_r(x) if z[0]==l[0]: outp += z[1:] else: outp.append(z) else: outp.append(x) return outp
essentially, these go through , check saying.
update:
if you'd rather able operate on generic sequences, work: checks if sequence, , makes sure isn't string:
import collections def condense(l): outp = [l[0]] x in l[1:]: if isinstance(x,collections.sequence) \ , not isinstance(x,basestring) , x[0]==l[0]: outp += x[1:] else: outp.append(x) return outp def condense_r(l): outp = [l[0]] x in l[1:]: if isinstance(x,collections.sequence) , not isinstance(x,basestring): z = condense_r(x) if z[0]==l[0]: outp += z[1:] else: outp.append(z) else: outp.append(x) return outp
Comments
Post a Comment