Hi everyone again, yet another question on lists
consider this list:
Python Code:
mylist=[]mylist.append(['B2', ['C3', 'C4', ['D5', 'D6']], 'B7','B8', ['C9', [[['F10'],'E11'],'D12']]])
I want to iterate through all the contents and for every string that contains 'B' to remove them and place all of them in a new sublist one level deeper in a way that the list prints
I've using list.remove(item) while in a 'for item in list' loop and it reduces the index by one messing up everything.Python Code:
[['B2','B7','B8'], ['C3', 'C4', ['D5', 'D6']], ['C9', [[['F10'],'E11'],'D12']]]
so i decided to create a new list with the Strings positioned the way i want:
Python Code:
def NewList(thelist):sublist = []sublist2=[]newlist= []for item in thelist:if hasattr(item,"__iter__"):for subitem in item:sublist.append(subitem)elif "B" in item:sublist2.append(item)else:newlist.append(item)newlist.append(sublist2)if sublist: newlist.append(NewList(sublist))return newlist
but this returns:
python Code:
[[], [['B2', 'B7', 'B8'], ['C3', 'C4', 'C9', [], ['D5', 'D6', 'D12', [], ['E11', [], ['F10', []]]]]]]
and i don't understand what are the empty slots or the extra brackets...
any help appreciated !
regards,
Pav


Reply With Quote
.
