0

i have a list like

lst = [[1,[2,[3,4,[7,8],5,6]]],[['a',['b',['c','d',['g','h'],'e','f']]]]]

i need to validate each time, if the current list item is a list or a single item(in this case a int/str)

If found a list again iterate that list, if found as a single element put it in a new list.

so at last i need 2 new list in particular order

new1 = [1,2,3,4,5,6,7,8]
new2 = ['a','b','c','d','e','f','g','h']

filtering is like outermost first then 2nd inner then 3rd inner...so on.

Can any body provide a code for it. Thanks in Advance.

Satya
  • 5,470
  • 17
  • 47
  • 72

1 Answers1

1
lst = [[1,[2,[3,4,[7,8],5,6]]],[['a',['b',['c','d',['g','h'],'e','f']]]]]

def rec(x):
    if isinstance(x,list):
        for k in x:
            rec(k)
    else:
        rec.y.append(x)

rec.y=[]
for i in lst:
    rec(i)
    print rec.y
    rec.y=[]

Output:[1, 2, 3, 4, 7, 8, 5, 6] ['a', 'b', 'c', 'd', 'g', 'h', 'e', 'f']

vks
  • 67,027
  • 10
  • 91
  • 124
  • @vks-the order is not matching ---outer -inner1-inner2...likewise....Expected was [1,2,3,4,5,6,7,8] – Satya Dec 29 '15 at 06:52