parse list recurisively

A

andypu

Hello,

i use a load of lists and often i dont know how deep it is, how can i parse that lists elegantly (without a bunch of for loops)
 
C

Chris Angelico

Hello,

i use a load of lists and often i dont know how deep it is, how can i parse that lists elegantly (without a bunch of for loops)

You can write a function that calls itself - that's what "recursive"
usually means in programming. Start with the tutorial on functions, or
just search the web for 'python recursive function'. Once you have a
bit of code down, you'll be able to ask a more specific question.

Have fun!

ChrisA
 
A

andypu

thanks i was not able to figure it out some days before but now i think i can do it myself: a nice function that searches a string in a list.

def parsesb(lis, string):
print lis
for num, nam in enumerate (lis):
print num, nam
if type(nam) == list: parsesb(lis[num],string)
if type(nam) == str: # do something
if nam == string: print 'hit!!!'
 
O

Oscar Benjamin

Hello,

i use a load of lists and often i dont know how deep it is, how can i parse that lists elegantly (without a bunch of for loops)

I don't really understand what you mean. Can you show some code that
illustrates what you're doing?

http://sscce.org/


Oscar
 
A

andypu

i have a list and i want to search for a certain string and replace it.

i think i got it now...

sbxe1 = list([['type','ter',[[[['lala']]]]],'name'])
def parsesb(lis, string, replacement):
for num, nam in enumerate (lis):
if type(nam) == list:
parsesb(lis[num],string,replacement)
if type(nam) == str: # do something
if nam == string: lis[num] = replacement
parsesb(sbxe1 ,'name', 'booooogyman')
print sbxe1
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,100
Messages
2,570,635
Members
47,242
Latest member
BarrettMan

Latest Threads

Top