Say you have a list of lists stored in mylist
.
mylist = [[1,2], [5,4], [9,10], [11,11], [18,10]]
Here are some useful methods to play with the data inside.
mycolumns = [list(col) for col in zip(*mylist)] print mycolumns
Output: [[1, 5, 9, 11, 18], [2, 4, 10, 11, 10]]
Thus, if you want to take, for example, the average per “column” in mylist
, it will just be
import numpy as np myaverages = [np.mean(col) for col in zip(*mylist)] print myaverages
Output: [8.8000000000000007, 7.4000000000000004]
Note that zip
is a Python built-in function that “returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables“.
mylist = [[1,2], [5,4], [9,10], [11,11], [18,10]] print zip(mylist)
Output: [([1, 2],), ([5, 4],), ([9, 10],), ([11, 11],), ([18, 10],)]
print zip(*mylist)
Output: [(1, 5, 9, 11, 18), (2, 4, 10, 11, 10)]
If, on the other hand, you have two lists x
and y
,
x = [1,2,3,4,5] y = [10,11,12,13,14] print zip(x, y)
Output: [(1, 10), (2, 11), (3, 12), (4, 13), (5, 14)]