python trick

Some elegant elements of writing python.

  • transpose
1
2
3
4
5

mat = [[1,2,3],[4,5,6]]
transpose = zip(*mat) # unpack mat
print(list(transpose))
# [[1,4], [2,5], [3,6]]
  • chained function call
1
2
3
4
5
6
7
8
9

def product(a,b):
return a * b

def add(a,b):
return a + b

flag = True
print((product if flag else add)(5,7))
  • sort Dictionary by Value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dic = {
"a":132
"b":214
"d":44
}

# 1
sorted(dic.items(), key=lambda x: x[1])

# 2
from operator import itemgetter
sorted(dic.items(), key=itemgetter(1))

# 3
sorted(dic, key=dic.get)
  • merget dict
1
2
3
4
5
6
7
8
d1 = {1:2}
d2 = {2:3}

# just for python 3.5
# 1
{**d1, **d2}
dict(d1.items() | d2.items())
d1.update(d2)
Share