transforming a list into a string

Steven Rumbalski srumbalski at copper.net
Sun Aug 1 22:03:46 CEST 2004


Peter Otten wrote:

Peter's solution:
>>>> 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}'

My first thought was:

>>> items = ['1','2','7','8','12','13']
>>> ",".join(["{%s,%s}" % i for i in zip(items[::2], items[1::2])])
 '{1,2},{7,8},{12,13}'

Two lines less, but it creates three unnecessary lists.  I like
Peter's better.

--Steven Rumbalski



More information about the Python-list mailing list