日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python从题目中学习:random() module

發布時間:2025/5/22 python 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python从题目中学习:random() module 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近在給公司培訓Python,布置了一道題:

-------------------------------------------------------------------------------------------

Generate 10 random floats(value range is (-2.0,2.0) and precision is 1) and save as list;

Such as: [-0.7, 0.8, 1.6, 0.1, 0.3, -1.0, 0.4, 1.0, 0.5, 0.7] ;

-------------------------------------------------------------------------------------------

因為用到了random模塊,在此做一個總結:

?

random()

類似于uniform(),只不過下限恒等于0.0,上限恒等于1.0

randint()

兩個整型參數,返回二者之間的隨機整型

randrange()

它接受和range()函數一樣的參數,隨機返回range([start,]stop[,step])結果的一項

uniform()

幾乎和randint()一樣,不過他返回的是二者之間的一個浮點型(不包括范圍上限)

sample(seq,k)

從指定序列中隨機獲取指定長度的片斷

choice()

隨機返回給定序列的一個元素

shuffle()

用于將一個列表中的元素打亂

?

random模塊用于生成隨機數,下面列舉幾個常用的函數。

①random.random

| random(...)
| random() -> x in the interval [0, 1).

random.random()用于生成一個0到1的隨機符點數: 0 <= n < 1.0

>>> random.random() 0.7361643505007011

②random.uniform

|?uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.

random.uniform(a, b),用于生成一個指定范圍內的隨機符點數。

如果 a>b,則生成的隨機數n在[a,b]之間: a <= n <= b;

如果 a<b,則生成的隨機數n在[a,b]之間: b <= n <= a。

>>> random.uniform(10,20) 18.084480262346535 >>> random.uniform(20,10) 12.289824189134892

③random.choice

| choice(self, seq)
| Choose a random element from a non-empty sequence.

random.choice(self, seq)會從序列中獲取一個隨機元素。

參數seq表示一個有序類型。字符串,list,tutple都屬于sequence。

>>> random.choice("PythonRandomModule")#字符串 'P' >>> random.choice(["Delon","is","a","nice","boy"])#列表 'a' >>> random.choice(("Tuple1","Tuple2","Tuple3"))#元組 'Tuple1'

?

④random.randint

| randint(self, a, b)
| Return random integer in range [a, b], including both end points.

random.randint(a, b),用于生成一個指定范圍內的整數。生成的隨機數n在[a,b]之間: a <= n <= b。(結束點b必須大于起始點a。)

>>> random.randint(2,10)#隨機數在[2,10]之間 8 >>> random.randint(10,10)#結果永遠是10 10 >>> random.randint(10,2)#語法錯誤 raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width) ValueError: empty range for randrange() (10,3, -7)

?

⑤random.randrange

| randrange(self, start, stop=None, step=1, _int=<type 'int'>, _maxwidth=9007199254740992L)
| Choose a random item from range(start, stop[, step]).
|?
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.

random.randrange([start], stop[, step]) 在指定范圍內,獲取一個隨機數從 指定的step生成的遞增集合中。

比如random.randrange(10,100,2),就相當于從[10,12,14,16,18,.....,94,96,98]的序列中獲取一個隨機數。

random.randrange(10,100,2)與random.choice(range(10,100,2))一樣。

>>> random.randrange(10,100,2) 48 >>> random.choice(range(10,100,2)) 18

?

⑥random.sample

| sample(self, population, k)
| Chooses k unique random elements from a population sequence.
|?
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|?
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
| selection in the sample.
|?
| To choose a sample in a range of integers, use xrange as an argument.
| This is especially fast and space efficient for sampling from a
| large population: sample(xrange(10000000), 60)
|

random.sample(sequence, k),從指定序列中隨機獲取指定長度的片斷。

>>> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> slice = random.sample(list,5) >>> slice [6, 5, 10, 9, 2] >>> list#原序列不會因為sample而改變 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

?

⑦random.shuffle

| shuffle(self, x, random=None)
| x, random=random.random -> shuffle list x in place; return None.
|
| Optional arg random is a 0-argument function returning a random
| float in [0.0, 1.0); by default, the standard random.random.
random.shuffle(x[, random]),用于將一個列表中的元素打亂。

>>> list = ["Python","is","powerful","languange"] >>> random.shuffle(list) #打亂 >>> list ['powerful', 'is', 'languange', 'Python']

?-----------------------------------------------------------------------------------------

?接下來舉幾個例子:

例子1:(參考http://www.cnblogs.com/yd1227/archive/2011/03/18/1988015.html):

#隨機生成[0,99]的整數: >>> import random >>> random.randint(0,99) 21#隨機選取0到100間的偶數: >>> random.randrange(0, 101, 2) 42#隨機浮點數: >>> random.random() 0.85415370477785668 >>> random.uniform(1, 10) 5.4221167969800881#隨機字符: >>> import random >>> random.choice('abcdefg&#%^*f') 'd'#多個字符中選取特定數量的字符: >>> random.sample('abcdefghij',3) ['a', 'd', 'b']#多個字符中選取特定數量的字符組成新字符串: >>> import string >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).replace(" ","") 'fih'#隨機選取字符串: >>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ) 'lemon'#洗牌: >>> import random >>> items = [1, 2, 3, 4, 5, 6] >>> random.shuffle(items) >>> items [3, 2, 5, 6, 4, 1]

?

例子2:(參考http://blog.csdn.net/xiaocaiju/article/details/6973175):

import random result = random.random() print result   #生成0-1的隨機數 0.6595765656210394print random.uniform(10,12) #10-12的隨機數 10.806990108392618 print random.randint(30,50)  #30-50的隨機整數 50print random.randrange(10,100,2) #從10開始到100結束,步長為2的序列中,隨機選一個 22list = [1,2,5,6,7,8,8] print random.choice(list) #從序列中隨機選一個 5random.shuffle(list) #重新排列序列 print list [5, 2, 1, 6, 8, 8, 7]list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) #從序列中取樣 print slice [7, 3, 2, 5, 10]

?

現在回到文章開頭的問題,代碼如下:

""" Generate 10 random floats(value range is (-2.0,2.0) and precision is 1) and save as list;Such as: [-0.7, 0.8, 1.6, 0.1, 0.3, -1.0, 0.4, 1.0, 0.5, 0.7] ;""" >>> [round(random.uniform(-2,2),1) for i in range(10)] #[-1.0, -1.0, -1.7, 1.0, -1.1, 1.9, 1.7, 0.2, -0.9, 1.1]

?

轉載于:https://www.cnblogs.com/dzblog/p/3924813.html

總結

以上是生活随笔為你收集整理的Python从题目中学习:random() module的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。