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),從指定序列中隨機獲取指定長度的片斷。
?
⑦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]),用于將一個列表中的元素打亂。
?-----------------------------------------------------------------------------------------
?接下來舉幾個例子:
例子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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: struts2 学习记录 之 国际化
- 下一篇: 无限循环的ViewPager