transforming a list into a string

Bengt Richter bokr at oz.net
Sun Aug 1 14:06:59 EDT 2004


On Sun, 1 Aug 2004 11:00:32 +1000, Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote:

>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...).
>
Assuming items definition doesn't count in the line count,

 >>> items = ['1','2','7','8','12','13']

then one line seems to do it, not that obscurely (depending on your glasses ;-)

 >>> ",".join(["{%s,%s}"%(n(),n()) for n in [iter(items).next] for i in xrange(0,len(items),2)])
 '{1,2},{7,8},{12,13}'

>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.
Agreed.

Regards,
Bengt Richter



More information about the Python-list mailing list