国产欧美日韩第一页|日本一二三不卡视频|在线精品小视频,亚洲第一免费播放区,metcn人体亚洲一区,亚洲精品午夜视频

python中的隨機函數(shù)小結(jié)

2018-01-30 08:06:12 5755

1. random()函數(shù) 

描述:random() 方法返回隨機生成的一個實數(shù),它在[0,1)范圍內(nèi)。    

語法: 

1
2
import random
random.random();

注意:random()是不能直接訪問的,需要導(dǎo)入 random 模塊,然后通過 random 靜態(tài)對象調(diào)用該方法。 

實例演示: 

1
2
3
4
5
>>> import random
>>> print random.random();
0.803119901575
>>> print random.random();
0.451592468747

2. randrange()函數(shù)

描述: randrange() 方法返回指定遞增基數(shù)集合中的一個隨機數(shù),基數(shù)缺省值為1。返回一個整數(shù)

語法

1
2
import random
random.randrange ([start,] stop [,step])

參數(shù):

  1. start -- 指定范圍內(nèi)的開始值,包含在范圍內(nèi)

  2. stop -- 指定范圍內(nèi)的結(jié)束值,不包含在范圍內(nèi)。

  3. step -- 指定遞增基數(shù)

實例演示

1
2
3
4
5
6
7
8
>>> print random.randrange(10);
4
>>> print random.randrange(5,10);
7
>>> print random.randrange(5,10,3);
5
>>> print random.randrange(5,10,3);
8

3.randint()函數(shù)

描述:randint()方法將隨機生成一個整數(shù),它在[x,y]范圍內(nèi) ;有點等價于randrange(x,y+1).

語法 

1
2
import random
random.randint(x,y)

參數(shù):

  1. x -- 指定范圍內(nèi)的開始值,包含在范圍內(nèi)

  2. y -- 指定范圍內(nèi)的結(jié)束值,包含在范圍內(nèi)。

實例演示

1
2
3
4
>>> print random.randrange(5,10);
9
>>> print random.randint(5,10);
6

4. uniform()函數(shù)

描述:uniform() 方法將隨機生成下一個實數(shù),它在[x,y]范圍內(nèi)。返回一個浮點數(shù) 

語法:

1
2
import random
random.uniform (x,y)

參數(shù):

  1.  x -- 指定范圍內(nèi)的開始值,包含在范圍內(nèi)

  2. y -- 指定范圍內(nèi)的結(jié)束值,包含在范圍內(nèi)。

實例演示

1
2
3
4
>>> print random.uniform(5,10);
9.13282585434
>>> print random.uniform(9,10);
9.95958315062

5. choice()函數(shù)

描述:choice() 方法返回一個列表,元組或字符串的隨機項。

語法

1
2
import random
random.choice(x)

參數(shù):

x -- list,tuple,strings的一種

實例演示

1
2
3
4
5
6
>>> print random.choice(('a','be',5,'e'))
5
>>> print random.choice([10,2,6,5,85,'af'])
85
>>> print random.choice('i love python')
v

6. sample()函數(shù)

描述:sample()方法返回隨機從列表,元組或字符串其中部分隨機項 ;返回類型為元組類型

語法

1
2
import random
random.sample(x,n)

參數(shù):

  1. x -- list,tuple,strings的一種

  2. n -- 返回n個隨機項

實例演示

1
2
3
4
5
6
>>> print random.sample('i love python',3)
[' ', 'e', 'i']
>>> print random.sample([10,20,50,23,'ab'],3)
[50, 'ab', 23]
>>> print random.sample((10,20,50,23,'ab'),3)
[50, 20, 'ab']

7. shuffle()函數(shù)

描述:shuffle() 方法將序列的所有元素隨機排序。類似于洗牌

語法 : 

1
2
import random
random.shuffle(x)

參數(shù):

  1.  x -- list,tuple的一種;python2.x只支持list類型

實例演示

1
2
3
4
>>> list=['a','b','c','d','e'];
>>> random.shuffle(list);
>>> print list;
['c', 'd', 'a', 'e', 'b']

拓展:將元祖反轉(zhuǎn);實現(xiàn)reverse函數(shù)的效果

1
2
3
4
>>> list=['a','b','c','d','e'];
>>> list1=list[::-1]
>>> print list1
['e', 'd', 'c', 'b', 'a']


提交成功!非常感謝您的反饋,我們會繼續(xù)努力做到更好!

這條文檔是否有幫助解決問題?

非常抱歉未能幫助到您。為了給您提供更好的服務(wù),我們很需要您進一步的反饋信息:

在文檔使用中是否遇到以下問題: