A Byte of my 2.2-lb Brain

Just sharing stuff…

Python Built-In Function Zip

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)]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on June 25, 2015 by in Geek and tagged , .
%d bloggers like this: