Something about Python


[TOC]


lstrip()和rstrip()

1
2
str.lstrip([chars]) # 删除字符串左边的空格或指定字符
str.rstrip([chars]) # 删除字符串末尾的空格或指定字符

字典中找最值

1
2
3
dogdistance = {'dog-dog': 33, 'dog-cat': 36, 'dog-car': 41, 'dog-bird': 42}
min(dogdistance, key=dogdistance.get) # 返回最小值的键值:’dog-dog‘
max(dogdistance, key=dogdistance.get) # 返回最大值的键值:’dog-bird‘

列表中找最值

1
2
3
c = [-10,-5,0,5,3,10,15,-20,25]
print c.index(min(c)) # 返回最小值的索引
print c.index(max(c)) # 返回最大值的索引

字典按照value排序

返回list:

1
sorted(d.items(),key = lambda x:x[1],reverse = True)

1
2
import operator
sorted(d.items(),key = operator.itemgetter(1))

返回只有键的tuple

1
sorted(d,key=d.__getitem__)


numpy array 找最值

1
2
3
4
5
6
7
8
9
10
11
12
a = np.arange(9).reshape((3,3))
a
array([[0, 1, 2],
[9, 4, 5],
[6, 7, 8]])

print(np.max(a)) #全局最大
8
print(np.max(a,axis=0)) #每列最大
[6 7 8]
print(np.max(a,axis=1)) #每行最大
[2 5 8]
1
2
3
4
print(np.where(a==np.max(a)))
(array([2], dtype=int64), array([2], dtype=int64))
print(np.where(a==np.max(a,axis=0)))
(array([2, 2, 2], dtype=int64), array([0, 1, 2], dtype=int64))

List做除法

1
list(map(lambda x: x//4, list_a))