Packing list elements into tuples
Thorsten Kampe
thorsten at thorstenkampe.de
Wed Nov 10 01:53:17 CET 2004
* Nickolay Kolev (2004-11-09 22:29 +0100)
> I have a list whose length is a multiple of 3. I want to get a list of
> tuples each of which has 3 consecutive elements from the original list,
> thus packing the list into smaller packets. Like this:
>
> l = [1,2,3,4,5,6]
>
> tups = [(1,2,3), (4,5,6)]
>
> or
>
> l = [1,2,3,4,5,6,7,8,9]
>
> tups = [(1,2,3), (4,5,6), (7,8,9)]
Fragment[1] from a general purpose partitioning utility:
def part(seq, slice):
""" partition seq """
return [seq[slice * index:slice * (index + 1)]
for index in range(len(seq) / slice + bool(len(seq) % slice))]
> if i can dictionaries it would be even better:
>
> l = [1,2,3,4,5,6]
>
> tups = [
> {'first':1,'second':2,'third':3},
> {'first':4,'second':5,'third':6}
> ]
You're losing order and therfore you're attaching 'first', 'second'
and so on because you obviously need the original order. So don't use
a dictionary.
Thorsten
[1] Just for the record:
def part(seq, slice = None, modus = None):
"""
partition seq
syntax:
part(seq, boolean_function, modus = 'bool')
-> [[first_true_items], [first_false_item, remaining_items]]
part('str', 'separator', modus = 'sep') or
part('str', ['separators'], modus = 'sep')
part(list, item, modus = 'sep')
part(n, modus = 'set')
-> len([all_possible_partitions_of_[0, 1, ..., n]])
part(list, modus = 'set'
-> [all_possible_partitions_of_list]
part(seq, int, modus = 'size')
-> [seq0, seq1, ..., seqn] - where len(seq(i)) = int
part(seq, [n0, n1, ..., n(i)], modus = 'size'
-> [seq0, seq1, ..., seq(i)] - where len(seq(i)) = n(i)
"""
More information about the Python-list
mailing list