how can a list:
['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
elegantly be transformed to a list of tuples:
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]
in python?
Something like %2
to form tuples maybe?
how can a list:
['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
elegantly be transformed to a list of tuples:
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]
in python?
Something like %2
to form tuples maybe?
You can use the step portion of the slice syntax to step over every other element, and zip together the two slices, each starting at the 0th and 1st element respectively:
x = ['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
list(zip(x[::2], x[1::2]))
# returns:
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]
I think you should group the elements in your list in groups of two, and convert that group into a tuple as follows:
>>> l = ['tuple1_1', 'tuple1_2', 'tuple2_1', 'tuple2_2']
>>> N = 2
>>> subList = [tuple(l[n:n+N]) for n in range(0, len(l), N)]
>>> sublist
[('tuple1_1', 'tuple1_2'), ('tuple2_1', 'tuple2_2')]
lis = [1,2,3,4]
list(zip(*([iter(lis)]*2)))
This returns
[(1,2), (3,4)]
The list can be composed of any other data types.
For grouping some other list into tuples of length n,
just replace 2 with n.