Reputation: 4439
I have the following list. In python it looks like [15,20,25,35,-20... etc]
15 20 25 35 -20 -15 -10 -5
10 15 20 25 -25 -20 -15 -10
5 10 15 20 -35 -25 -20 -15
I want to nest vertically like so:
[[15,10,5],[20,15,10],[25,20,15],[35,25,20],[-20,-25,-35],...etc]
So it involves some kind of a transpose operation, but counting backwards, e.g. transpose would give you [5,10,15]
and not [15,10,5]
for the first item in the list
What's the best way to do it? (shortest and most readable code)
If anybody also have suggestions on shortest run time would be also helpful for bigger datasets.
Upvotes: 1
Views: 100
Reputation: 46533
from pprint import pprint
from operator import itemgetter
lst = [15, 20, 25, 35, -20, -15, -10, -5, 10, 15, 20, 25, -25,\
-20, -15, -10, 5, 10, 15, 20, -35, -25, -20, -15]
# Python 3
l = len(lst) // 3
# Or a single slash in Python 2: l = len(lst) / 3
# Just for diversity
a = [itemgetter(*range(x, x+l))(lst) for x in range(0, len(lst), l)]
pprint(list(zip(*a)))
Output:
[(15, 10, 5),
(20, 15, 10),
(25, 20, 15),
(35, 25, 20),
(-20, -25, -35),
(-15, -20, -25),
(-10, -15, -20),
(-5, -10, -15)]
Upvotes: 2
Reputation: 239463
You can group the elements with the list comprehension and then transpose it with zip
function, like this
data = [15, 20, 25, 35, -20, -15, -10, -5, 10, 15, 20,
25, -25, -20, -15, -10, 5, 10, 15, 20, -35, -25, -20, -15]
length = len(data) / 3
data = [data[i:i + length] for i in xrange(0, len(data), length)]
Till this point we grouped the data like this
[[15, 20, 25, 35, -20, -15, -10, -5],
[10, 15, 20, 25, -25, -20, -15, -10],
[5, 10, 15, 20, -35, -25, -20, -15]]
Now, we just have to transpose data
, with zip
print zip(*data)
Output
[(15, 10, 5),
(20, 15, 10),
(25, 20, 15),
(35, 25, 20),
(-20, -25, -35),
(-15, -20, -25),
(-10, -15, -20),
(-5, -10, -15)]
zip(*data)
means we unpack all the elements of data
and pass each of the elements as parameters to zip
. It is equivalent to
zip(data[0], data[1], data[2])
Upvotes: 3