Monday, August 31, 2015

[Python] Tricks list

Since I started learning Python, I didn't maintain any list of "tricks" for revisit and because of that my coding style is kind of outdated. Now I decide any time I see a piece of useful code in the sites such as Stack Overflow, I will add it to the list. If you are also learning Python, you might find quite a few of them you didn't know about and surprisingly useful, like I did.
Just so you know, I build this list based on this nice blog, which inspires me to make a similar list.

1. Define and swap variables

>>> a, b, c = (2 * i + 1 for i in range(3))
>>> a, b, c
(1, 3, 5)

>>> a, b = 1, 2
>>> a, b = b, a
>>> a, b
(2, 1)

2. Slicing and negative indexing

>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a[::2]
[0, 2, 4, 6, 8, 10]
a[-1]; a[-4:-2] # last element; last fourth to second element

>>> a
[1, 8, 9, 2, 0, 0, 4, 5]
>>> a[1:-1] = [] # delete some list elements
>>> a
[1, 5]

3. Flip up/down array

a[::-1] 

4. Iteration

enumerate: Iterating over list index and value pairs

>>> a = ['Hello', 'world', '!']
>>> for i, x in enumerate(a):
...     print '{}: {}'.format(i, x)  # look at the usage of dictionary
...
0: Hello
1: world
2: !

dict.iteritems: Iterating over dictionary key and values pairs

>>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> for k, v in m.iteritems():
...     print '{}: {}'.format(k, v)
...
a: 1
c: 3
b: 2
d: 4

4. Flatten a list

>>> a = [[1, 2], [3, 4], [5, 6]]
>>> list(itertools.chain.from_iterable(a))
[1, 2, 3, 4, 5, 6]

>>> sum(a, [])
[1, 2, 3, 4, 5, 6]

>>> [x for l in a for x in l]
[1, 2, 3, 4, 5, 6]

>>> a = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
>>> [x for l1 in a for l2 in l1 for x in l2]
[1, 2, 3, 4, 5, 6, 7, 8]

>>> a = [1, 2, [3, 4], [[5, 6], [7, 8]]]
>>> flatten = lambda x: [y for l in x for y in flatten(l)] if type(x) is list else [x]
>>> flatten(a)
[1, 2, 3, 4, 5, 6, 7, 8]

5. Flatten an array

Turn Nx1 NumPy array into 1D array

arr1d = np.ravel(arr2d)    
arr1d = arr2d.ravel()
arr1d = arr2d.flatten()
arr1d = np.reshape(arr2d, -1)
arr1d = arr2d[0, :]