Printing with interspersed element
invalid at invalid
Thu Oct 30 22:40:17 CET 2008
On 2008-10-30, Paulo J. Matos <pocmatos at gmail.com> wrote:
> On Thu, Oct 30, 2008 at 8:42 PM, Arnaud Delobelle
><arnodel at googlemail.com> wrote:
>> On Oct 30, 8:07 pm, "Paulo J. Matos" <p... at ecs.soton.ac.uk> wrote:
>>> 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?
>> Defining a print_obj() method is probably a bad idea. What if you
>> want to print to a file for example? Instead you can define a
>> __str__() method for your objects and then use the join() method of
>> strings like this:
>> print ' 10 '.join(str(x) for x in lst)
> Thanks for the tip but that has an issue when dealing with potentially
> millions of objects. You are creating a string in memory to then dump
> to a file [or screen] while you could dump to the file [or screen] as
> you go through the original string. Right?
If you want to do it "on the fly", then try something like this:
iter = [1,2,3,4,5].__iter__()
for n in iter:
Grant Edwards grante Yow! The SAME WAVE keeps
at coming in and COLLAPSING
visi.com like a rayon MUU-MUU ...
More information about the Python-list