python-->random模塊

random模塊

1、random模塊

# 大於0 而且小於1之間的小數
import random
print(random.random())
# 隨機輸出一個在1-3之間的整數
import random
print(random.randint(1,3))
# 隨機輸出一個1到2 的整數
import random
print(random.randrange(1,3))
# 隨機輸出一個大於1 小於3 的小數
import random
print(random.uniform(1,3))
# 隨機從列表內取一個元素進行輸出
import random
print(random.choice([1,2,'23',[4,5]]))
import random
lis = [1,2,3,4,5]
print(random.choices(lis))
#隨機從列表內取一個元素進行輸出,輸出一個列表形式
# random.sample([], n),列表元素任意n個元素的組合,示例n=3,組合成列表
import random
print(random.sample([1,2,'24',[4,5]],3))
#打亂順序
import random
lis = [1,2,3,4,5]
random.shuffle(lis)
print(lis)
#[2, 3, 5, 4, 1]

Python保留指定位數的小數

1 ’%.2f’ %f 方法(推薦)
2 format函數(推薦)
3 round()函數
4 不進行四捨五入,直接進行截斷dom

1 ’%.2f’ %f 方法(推薦)

f = 1.23456函數

print('%.4f' % f)
print('%.3f' % f)
print('%.2f' % f)
1
2
3
4
5
結果:
1.2346
1.235
1.23
這個方法會進行四捨五入code

2 format函數(推薦)

print(format(1.23456, '.2f'))
print(format(1.23456, '.3f'))
print(format(1.23456, '.4f'))
1
2
3
1.23
1.235
1.2346
1
2
3
這個方法會進行四捨五入orm

3 round()函數

其實這個方法不推薦你們使用,查詢資料發現裏面的坑其實不少,python2和python3裏面的坑還不太同樣,在此簡單描述一下python3對應的坑的狀況。字符串

a = 1.23456
b = 2.355
c = 3.5
d = 2.5
print(round(a, 3))
print(round(b, 2))
print(round(c))
print(round(d))
1
2
3
4
5
6
7
8
1.235 # 1.23456最終向前進位了
2.35 # 2.355竟然沒進位
4 # 最終3.5竟然變爲4了
2 # 最終2.5取值變爲2
1
2
3
4
(1)經過上面的函數,看着是否是很暈,感受round(x,n)函數是否進位也沒看出是啥規律
(2)round(x,n)函數中,是否進位或四捨五入,取決於n位以及n+1位小數的值
(3)只有當n+1位數字是5的時候,容易混淆,若是n爲偶數,則n+1位數是5,則進位,例如round(1.23456,3)最終變爲1.235
(4)若是n爲奇數,則n+1位是數5,那不進位,例如round(2.355,2),最終爲2.35
(5)若是n爲0,即沒有填寫n的時候,最終結果與上面相反,即整數部分爲偶數的時候,小數位5不進位,例如(round(2.5)變爲2)。
(6)整數部分爲奇數的時候,小數位5進位。(round(3.5)變爲4)
————————————————it

4 不進行四捨五入,直接進行截斷

(1)能夠放大指定的倍數,而後取整,而後再除以指定的倍數。form

保留三位小數截斷 python3

print(int(1.23456 * 1000) / 1000 )
1
2class

(2) 使用字符串截取,截取小數點後指定的位數import

相關文章
相關標籤/搜索