P
Paulo J. Matos
Hi all,
I guess this is a recurring issue for someone who doesn't really know
the python lib inside out. There must be a simple way to do this.
I have a list of objects [x1, x2, x3, ..., xn] and I have defined a
print method for them print_obj(). Now I want to print them
intersepersed by an element.
If I print [x1, x2, x3] interspersed by the element 10:
x1.print_obj() 10 x2.print_obj() 10 x3.print_obj()
Now, the question is, what's the best way to do this?
I guess I could do this recursively.
def print(el, lst):
if len(lst) == 0:
return
elif len(lst) == 1:
lst[0].print_obj()
else:
lst[0].print_obj()
print el,
print(el, lst[1:])
Now, some considerations. This seems cumbersome (it may have errors
has I have not tested and was written directly to the mail, but the
idea is clear). From what I know lst[1:] creates a copy of lst without
the first element which is really not good memory-wise.
So, what would be the python way to do it?
Cheers,
I guess this is a recurring issue for someone who doesn't really know
the python lib inside out. There must be a simple way to do this.
I have a list of objects [x1, x2, x3, ..., xn] and I have defined a
print method for them print_obj(). Now I want to print them
intersepersed by an element.
If I print [x1, x2, x3] interspersed by the element 10:
x1.print_obj() 10 x2.print_obj() 10 x3.print_obj()
Now, the question is, what's the best way to do this?
I guess I could do this recursively.
def print(el, lst):
if len(lst) == 0:
return
elif len(lst) == 1:
lst[0].print_obj()
else:
lst[0].print_obj()
print el,
print(el, lst[1:])
Now, some considerations. This seems cumbersome (it may have errors
has I have not tested and was written directly to the mail, but the
idea is clear). From what I know lst[1:] creates a copy of lst without
the first element which is really not good memory-wise.
So, what would be the python way to do it?
Cheers,