創建二維數組的辦法
- 直接創建(不推薦)
- 列表生產式法(可以去列表生成式 - 廖雪峰的官方網站學習)
- 使用模塊numpy創建
舉個栗子:
創建一個3*3矩陣,並計算主對角線元素之和。
import numpy as np
a=np.random.randint(1,100,9).reshape(3,3) #生成形狀為9的一維整數數組
a=np.random.randint(1,100,(3,3)) #上面的語句也可以改為這個
print(a)
(m,n)=np.shape(a) # (m,n)=(3,3)
sum=0
for i in range(m):
for j in range(n):
if i==j:
sum+=a[i,j]
print(sum)
其中一次輸出: [[96 42 16] [19 14 92] [39 29 95]] 205
numpy中random:
- numpy.random.randint(low, high=None, size=None, dtype='l'):生成一個整數或N維整數數組,取數范圍:若high不為None時,取[low,high)之間隨機整數,否則取值[0,low)之間隨機整數。
#numpy.random.randint(low, high=None, size=None, dtype='l') import numpy as np #low=2 np.random.randint(2)#生成一個[0,2)之間隨機整數 #low=2,size=5 np.random.randint(2,size=5)#array([0, 1, 1, 0, 1]) #low=2,high=2 #np.random.randint(2,2)#報錯,high必須大於low #low=2,high=6 np.random.randint(2,6)#生成一個[2,6)之間隨機整數 #low=2,high=6,size=5 np.random.randint(2,6,size=5)#生成形狀為5的一維整數數組 #size為整數元組 np.random.randint(2,size=(2,3))#生成一個2x3整數數組,取數范圍:[0,2)隨機整數 np.random.randint(2,6,(2,3))#生成一個2x3整數數組,取值范圍:[2,6)隨機整數 #dtype參數:只能是int類型 np.random.randint(2,dtype='int32') np.random.randint(2,dtype=np.int32)
reshape()用法
arange()用於生成一維數組
reshape()將一維數組轉換為多維數組
舉個栗子:
import numpy as np print('默認一維為數組:', np.arange(5)) print('自定義起點一維數組:',np.arange(1, 5)) print('自定義起點步長一維數組:',np.arange(2, 10, 2)) print('二維數組:', np.arange(8).reshape((2, 4))) print('三維數組:', np.arange(60).reshape((3, 4, 5))) print('指定范圍三維數組:',np.random.randint(1, 8, size=(3, 4, 5)))
默認一維數組: [0 1 2 3 4] 自定義起點一維數組: [1 2 3 4] 自定義起點步長一維數組: [2 4 6 8] 二維數組: [[0 1 2 3] [4 5 6 7]] 三維數組: [[[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] [[20 21 22 23 24] [25 26 27 28 29] [30 31 32 33 34] [35 36 37 38 39]] [[40 41 42 43 44] [45 46 47 48 49] [50 51 52 53 54] [55 56 57 58 59]]] 指定范圍三維數組: [[[2 3 2 1 5] [6 5 5 6 7] [4 4 6 5 3] [2 2 3 5 6]] [[2 1 2 4 4] [1 4 2 1 4] [4 4 3 4 2] [4 1 4 4 1]] [[6 2 2 7 6] [2 6 1 5 5] [2 6 7 2 1] [3 3 1 4 2]]] [[[3 3 5 6] [2 1 6 6] [1 1 3 5]] [[7 6 5 3] [5 6 5 4] [6 5 7 1]]]
shape()用法
查看矩陣或者數組的維數
建立一個3×3的單位矩陣e, e.shape為(3,3)
參考博文:https://blog.csdn.net/kancy110/article/details/69665164
行走菜鳥界的小辣雞~