l=[1,[1,[1,[1,[1]]]]]
How to convert the above n dimension list into single dimension list without using any inbuilt functions. Here am looking for the logic.
output should be as [1,1,1,1,1]
Please help me on this
l=[1,[1,[1,[1,[1]]]]]
How to convert the above n dimension list into single dimension list without using any inbuilt functions. Here am looking for the logic.
output should be as [1,1,1,1,1]
Please help me on this
Use a recursion function:
In [20]: def ravel(lst):
for i in lst:
if isinstance(i, list): #use 'type(i) is list' if you don't want built-in functions
yield from ravel(i)
else:
yield i
....:
In [21]: list(ravel(l))
Out[21]: [1, 1, 1, 1, 1]
Here's a Python 2 solution that doesn't use any built-in functions.
Like the other solutions we use recursion. If the current item is a list we recurse into it, yielding whatever solutions are found to the previous recursion level. Otherwise we just yield the item.
def flatten(seq):
for u in seq:
try:
for v in flatten(u):
yield v
except TypeError:
yield u
l = [1, [2, [3, [4, [5]]]]]
flat = [u for u in flatten(l)]
print flat
output
[1, 2, 3, 4, 5]
Of course, using Python without any of its built-in functions is silly, unless it's for a programming puzzle. The sensible way to do this is:
def flatten(seq):
for u in seq:
if isinstance(u, list):
for v in flatten(u):
yield v
else:
yield u
l = [1, [2, [3, [4, [5]]]]]
flat = list(flatten(l))
In Python 3, you can use the yield from syntax, as shown in Kasramvd's answer.
def flatten(seq):
for u in seq:
if isinstance(u, list):
yield from flatten(u)
else:
yield u
l = [1, [2, [3, [4, [5]]]]]
flat = list(flatten(l))
print(flat)
Try this,
l = [1,[1,[1,[1,[1]]]]]
def getAsList(l):
r =[]
for i in l:
if type(i) == list:
r.extend(getAsList(i))
else:
r.append(i)
return r
print getAsList(l)
You could stretch the usage of try and except in order to get this done without isinstance
In [44]: def flatten(l, r):
...: for i in l:
...: try:
...: i.count
...: flatten(i, r)
...: except:
...: r.append(i)
In [46]: l=[1,[1,[1,[1,[1]]]]]
In [47]: r = []
In [48]: flatten(l,r)
In [49]: r
Out[49]: [1, 1, 1, 1, 1]