2020/03/01
1. random.randrange
返回指定遞增基數(shù)集合中的一個(gè)隨機(jī)數(shù),基數(shù)默認(rèn)值為1
語(yǔ)法:random.randrange ([start,] stop [,step])。
start -- 指定范圍內(nèi)的開(kāi)始值,包含在范圍內(nèi); stop -- 指定范圍內(nèi)的結(jié)束值,不包含在范圍內(nèi);step -- 指定遞增基數(shù)
randrange()方法返回指定遞增基數(shù)集合中的一個(gè)隨機(jī)數(shù),基數(shù)默認(rèn)值為1
例如:
輸出 100 <= number < 1000 間的偶數(shù)print "randrange(100, 1000, 2) : ", random.randrange(100, 1000, 2)
輸出 100 <= number < 1000 間的其他數(shù)print "randrange(100, 1000, 3) : ", random.randrange(100, 1000, 3)
輸出結(jié)果:
randrange(100, 1000, 2) : 976
randrange(100, 1000, 3) : 520
2. np.newaxis
np.newaxis的作用就是在這一位置增加一個(gè)一維,這一位置指的是np.newaxis所在的位置,示例如下:
x1 = np.array([1, 2, 3, 4, 5])
# the shape of x1 is (5,)
x1_new = x1[:, np.newaxis]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
x1_new = x1[np.newaxis,:]
# now, the shape of x1_new is (1, 5)
# array([[1, 2, 3, 4, 5]])
再比如:
In [124]: arr = np.arange(5*5).reshape(5,5)
In [125]: arr.shape
Out[125]: (5, 5)
# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]
In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)
3. numpy中np.max和np.maximum
np.max(a, axis=None, out=None, keepdims=False)
求序列的最值, 最少接受一個(gè)參數(shù), axis默認(rèn)為axis=0即列向,如果axis=1即橫向。
例如:
val = np.max([-2, -1, 0, 1, 2])
print(val) # 2
np.maximum(X, Y, out=None)
X和Y逐位進(jìn)行比較,選擇最大值,最少接受兩個(gè)參數(shù)
val = np.maximum([-3, -2, 0, 1, 2], 0)
print(val) # array([0, 0, 0, 1, 2])
4. np.prod()
用來(lái)計(jì)算所有元素的乘積,對(duì)于有多個(gè)維度的數(shù)組可以指定軸,如axis=1指定計(jì)算每一行的乘積.
默認(rèn)情況下計(jì)算所有元素的乘積:
import numpy as np
val = np.prod([1., 2.])
print(val) # 2.0
若輸入數(shù)據(jù)是二維的:
val = np.prod([[1, 2], [3, 4]])
print(val) # 24
也可以按照指定軸進(jìn)行運(yùn)算:
val = np.prod([[1,2], [3,4]])
print(val) # array([2, 14])