transforming a list into a string

Christopher T King squirrel at WPI.EDU
Sun Aug 1 18:33:33 EDT 2004


On Sat, 31 Jul 2004, Tim Peters wrote:

> Absolutely.  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}'
> >>>

A bit too clever for mine, mostly because neither izip() nor zip() is 
guaranteed to process its arguments in a left-to-right order (although 
there's no reason for them not to).  I'd rather do this:

>>> from itertools import izip, islice
>>> items = ['1','2','7','8','12','13']
>>> it1 = islice(items,0,None,2)
>>> it2 = islice(items,1,None,2)
>>> ",".join(["{%s,%s}" % i for i in izip(it1, it2)])
'{1,2},{7,8},{12,13}'

Although it doesn't improve efficiency any (or have that 'slick' feel), it 
does prevent needless head-scratching :)

Curious, why isn't slicing of generators defined, using islice(), so "it1 
= iter(items)[0::2]" is valid?




More information about the Python-list mailing list