iterate through an irregular nested list in Python
Pieter van Oostrum
pieter-l at vanoostrum.org
Fri Mar 6 15:54:40 EST 2020
sinndhhu at gmail.com writes:
> Hi All,
> I am new to python.
> I have a irregular nested lists in a list.
> Please help me to iterate through each element.
>
> Thanks much in advance.
>
> Sample Ex
>
> aList = [[2,'jkj'],[],[],['kite',88,'ooo','pop','push','pull'],['hello']]
>
> expected output:
> 2,jkj,,,kite,88,ooo,pop,push,pull,hello
>
Use a recursive iterator/generator: It becomes a bit peculiar because you want special treatment for empty lists inside,
but otherwise it is quite standard Python:
aList = [[2,'jkj'],[],[],['kite',88,'ooo','pop','push','pull'],['hello']]
def reclist(aList):
for item in aList:
if isinstance(item, list):
if item == []:
yield ''
else:
yield from reclist(item)
else:
yield item
for i in reclist(aList):
print(i, end=',')
This gives you an extra comma at the end, unfortunately. But it is the pattern for other types of processing.
Or use it like this:
print (','.join(str(i) for i in reclist(aList)))
--
Pieter van Oostrum
www: http://pieter.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
More information about the Python-list
mailing list