printing out elements in list
Tim N. van der Leeuw
tim.leeuwvander at nl.unisys.com
Mon May 8 04:04:31 EDT 2006
Using slices and built-in zip:
>>> alist = ['>QWER' , 'askfhs', '>REWR' ,'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' ]
>>> dict(zip(alist[::2], alist[1::2]))
{'>QWER': 'askfhs', '>FGDG': 'sdfsdgffdgfdg', '>REWR': 'sfsdf'}
Slightly more efficient might be to use izip from itertools:
>>> from itertools import izip
>>> dict(izip(alist[::2], alist[1::2]))
{'>QWER': 'askfhs', '>FGDG': 'sdfsdgffdgfdg', '>REWR': 'sfsdf'}
And perhaps using islice from iterools might improve efficiency even
more:
>>> from itertools import islice, izip
>>> dict(izip(islice(alist, 0, None, 2), islice(alist, 1, None, 2)))
{'>QWER': 'askfhs', '>FGDG': 'sdfsdgffdgfdg', '>REWR': 'sfsdf'}
(I didn't try to time any of these solutions so I have no real idea
which is more efficient, but using iterators from the itertools-module
should in theory mean you create less temporary objects; especially
with large lists this can be a win)
Cheers,
--Tim
More information about the Python-list
mailing list