生成隨機數(shù)
random模塊
常用函數(shù)
random() —— 生成一個[0,1.0)之間的隨機浮點數(shù)
uniform(a,b) —— 生成一個a到b之間的隨機浮點數(shù)
randint(a,b) —— 生成一個a到b之間的隨機整數(shù)
choice(<list>) —— 從列表中隨機返回一個元素
shuffle(<list>) —— 將列表中元素隨機打亂
sample(<list>,k) —— 從指定列表中隨機獲取k個元素
遍歷列表獲取每個元素的索引號及其元素值
enumerate()函數(shù)
enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表、元組或字符串)組合為一個索引序列,同時列出數(shù)據(jù)和數(shù)據(jù)下標(biāo),一般用在 for 循環(huán)當(dāng)中。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
list(enumerate(seasons, start=1)) # 下標(biāo)從 1 開始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
普通的for循環(huán):
i = 0
seq = ['one', 'two', 'three']
for element in seq:
... print i, seq[i]
... i += 1
...
0 one
1 two
2 three
for 循環(huán)使用 enumerate:
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three
將對應(yīng)點數(shù)和次數(shù)關(guān)聯(lián)起來
zip()函數(shù)
用于將對應(yīng)的元素打包成一個個元組
l1 = [1, 2, 3, 4, 5]
l2 = ['a', 'b', 'c', 'd', 'e']
zip(l1, l2)
[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
注意:元組中的元素是不可以修改的,若要修改需要轉(zhuǎn)換成字典或其他
如dict(zip(l1, l2))
可視化
matplotlib模塊
散點圖繪制
import matplotlib.pyplot as plt
# x, y分別是x坐標(biāo)和y坐標(biāo)的列表
plt.scatter(x, y)
plt.show()
直方圖繪制
plt.hist(data, bins(
data:數(shù)據(jù)列表
bins:分組邊界
邊界顏色edgecolor
邊界線寬度linewidth
頻率normed=1
plt.hist(roll_list, bins=range(2, 14), normed=1, edgecolor='black', linewidth=0.5)
解決中文顯示問題:
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
NumPy
Numeric Python:用Python實現(xiàn)的科學(xué)計算庫
包括:
1、強大的N維數(shù)組對象array
2、成熟的科學(xué)函數(shù)庫
3、實用的線性代數(shù)、隨機數(shù)生成函數(shù)等
NumPy的操作對象是多維數(shù)組ndarray
ndarray.shape 數(shù)組的維度
創(chuàng)建數(shù)組:np.array(<list>), np.arrange()…
改變數(shù)組的形狀 reshape()
NumPy創(chuàng)建隨機數(shù)組
np.random.randint(a, b, size)
創(chuàng)建[a, b)間形狀為size的數(shù)組
例如:
import numpy as np
arr = np.random.randint(1, 10, (3, 4))
print(arr)
