Python one-liners
How to use one-liners to perform common tasks
import numpy as np
Flatten a list
x = np.random.randint(100, size=(4, 5))
[i for j in x for i in j]
[99, 46, 16, 16, 50, 19, 96, 63, 57, 6, 36, 81, 98, 87, 30, 42, 24, 72, 39, 7]
Remove duplicate elements from list
x = np.random.randint(5, size=10)
x
array([2, 0, 0, 2, 0, 4, 2, 4, 3, 1])
list(set(x))
[0, 1, 2, 3, 4]
Most frequent element in the list
x = np.random.randint(5, size=20)
x
array([0, 1, 0, 1, 4, 2, 4, 4, 2, 1, 4, 0, 2, 0, 1, 1, 1, 1, 3, 2])
from collections import Counter
Counter(x).most_common()
[(1, 7), (0, 4), (4, 4), (2, 4), (3, 1)]
Counter(x).most_common()[0]
(1, 7)
Counter(x).most_common()[0][0]
1
Multiply all elemetns of a list
x = np.arange(1, 11)
x
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
np.prod(x)
3628800
from functools import reduce
reduce((lambda x,y: x*y), x)
3628800
Find indices of an element in a list
myarray = np.random.randint(8, size=20)
myarray
array([0, 1, 0, 0, 3, 5, 1, 3, 0, 0, 6, 3, 0, 6, 1, 4, 1, 5, 6, 4])
np.where(myarray==1)[0]
array([ 1, 6, 14, 16])
mylist = list(np.random.randint(8, size=20))
mylist
[7, 0, 2, 3, 0, 1, 5, 5, 7, 3, 1, 2, 1, 2, 3, 5, 1, 2, 0, 4]
[i for i in range(len(mylist)) if mylist[i] == 1]
[5, 10, 12, 16]