Packing list elements into tuples
Steven Bethard
steven.bethard at gmail.com
Tue Nov 9 17:27:58 EST 2004
Nickolay Kolev <nmkolev <at> uni-bonn.de> writes:
> l = [1,2,3,4,5,6]
>
> tups = [(1,2,3), (4,5,6)]
My favorite idiom:
>>> l = [1,2,3,4,5,6]
>>> zip(*(iter(l),)*3)
[(1, 2, 3), (4, 5, 6)]
>>> l = [1,2,3,4,5,6,7,8,9]
>>> zip(*(iter(l),)*3)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
If you want dicts, try:
>>> l = [1,2,3,4,5,6]
>>> tuples = zip(*(iter(l),)*3)
>>> labels = 'first second third'.split()
>>> [dict(zip(labels, t)) for t in tuples]
[{'second': 2, 'third': 3, 'first': 1}, {'second': 5, 'third': 6, 'first': 4}]
Basically, you can make a dict with whatever labels you want by zipping your
labels with the appropriate tuples and calling the dict builtin.
Steve
More information about the Python-list
mailing list