transforming a list into a string

Andrew Bennetts andrew-pythonlist at puzzling.org
Sun Aug 1 03:00:32 CEST 2004


On Sat, Jul 31, 2004 at 08:43:52PM -0400, Roy Smith wrote:
> Tim Peters <tim.peters at gmail.com> wrote:
> > Note that Peter Otten previously posted a lovely O(N)
> > solution in this thread, although it may be too clever for some
> > tastes:
> > 
> > >>> from itertools import izip
> > >>> items = ['1','2','7','8','12','13']
> > >>> it = iter(items)
> > >>> ",".join(["{%s,%s}" % i for i in izip(it, it)])
> > '{1,2},{7,8},{12,13}'
> 
> Personally, I'm not a big fan of clever one-liners.  They never seem 
> like such a good idea 6 months from now when you're trying to figure out 
> what you meant when you wrote it 6 months ago.

It's a two-liner, not a one-liner (although it could be made into a
one-liner with enough contortions...).

The only other way I could see to expand this solution would be to write it
as:
     it = iter(items)
     pairs = izip(it, it)
     s = ",".join(["{%s,%s}" % i for i in pairs])

I don't know if three-liners meet your threshold for verbosity ;)

Well, you could write it as:

    pairs = []
    it = iter(items):
    while True:
         try:
             pair = it.next(), it.next()
         except StopIteration:
             break
         pairs.append(pair)
    s = ",".join(["{%s,%s}" % i for i in pairs])
              
But at that point, the scaffolding is large enough that it obscures the
purpose -- I definitely find this harder to read than the two-liner.

I find Peter's original form easy to read -- if you understand how "izip(it,
it)" works (which is a very simple and elegant way to iterate over (it[n],
it[n+1]) pairs), the rest is very clear.

-Andrew.




More information about the Python-list mailing list