variable length print format

Gustavo Cordova gcordova at hebmex.com
Tue May 7 15:13:03 EDT 2002


> 
> Hi,
>

Gweepnings.

>
> i have a variable length list of numbers.
> i would like to print them out with indicies in front as shown below:
> 
> List=['a','b','c','d'] ---> 1:a 2:b 3:c 4:d
> 
> one obvious solution is that i do
> for i in range(List):
>   print "%s:%s" % (i+1,List[i])
> 

Another obvious solution (if you have Py >= 2.2)
would be list comprehension.

>
> however i have a lot of these and would like it to be faster so i 
> tried doing this 
> 
> formatstr=" %s:%s " * len(List)
> 
> print formatstr % (range(1,len(List)+1), List)
> 
> but it did not work.
> 

Of course not. :-)

You *could* create a function which returns a string
in the format you want, like:

def PairwiseList(lst):
   S = ""
   for i in range(len(lst)):
      S += "%s:%s " % (i+1, lst[i])
   return S


By using list comprehension you could shorten this a bit:


def PairwiseList(lst):
   L = [ "%s:%s" % (i+1, lst[i]) for i in range(len(lst)) ]
   return " ".join(L)


And, by using some functional wierd magic, you can shorten
it a bit more:


def PairwiseList(lst):
  return " ".join([ "%s:%s" % T for T in zip(xrange(1,len(lst)+1), lst) ])


and by using lambda, you can shorten it even more:


PWL = lambda L: " ".join(["%s:%s" % T for T in zip(xrange(1,len(L)+1),L)])

Oops!!! You wanted it to print!!

PWL = lambda L,W=__import__("sys").stdin.write: W([" ".join("%s:%s" % T for
T in zip(xrange(1,len(L)+1),L)]))

Which would be the proper answer to your question.

heh, sorry. It does work, but it looks hideous
("You can live off it, but it tastes like shit")

BTW, I used xrange() to make it more memory efficient.

/me ducks!

So, take your pick. :-)

-gustavo

pd: I apologize for being silly.
pdd: But it was fun though.





More information about the Python-list mailing list