Tricks

Python Tricks

Enumerate

enumerate 枚举的用法:

1
2
3
4
5
6
7
8
9
colors = ['red','green','yellow']
for i, name in enumerate(colors,0):
print(i,name)


out:
0 red
1 green
2 yellow

enumerate的第二个参数 代表 产生的index的起始

1
2
3
4
5
6
7
8
9
colors = ['red','green','yellow']
for i, name in enumerate(colors,1):
print(i,name)


out:
1 red
2 green
3 yellow

Zip

zip的用法:可以将两个list里的内容一一对应。

1
2
3
4
5
6
7
8
9
10
11
fruits = ['apple', 'orange']
colors = ['green','yellow']

for fruit, color in zip(fruits, colors):
print(fruit, color)



out:
apple green
orange yellow

Numpy Tricks

numpy.clip

np.clip(a, a_min, a_max , out=None)

a为数组,

当数组中的数小于a_min,则小于a_min的部分会被替换成a_min,

当数组中的数大于a_max,则大于a_max的部分会被替换成a_max。

若out指定为np.array a,则输出将会保存在a中

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