隨機數模組函式
- 最近使用了choice、shuffle 對於字典的處理,發現些問題,於是整理一下random模組中函式使用方法及一些問題
import random as rd
複製程式碼
函式
- random() #隨機獲取0~1之間的小數
- choice(lst/tuple/dict) #隨機獲取序列中的值,不可以操作集合,操作字典有時會出錯
- shuffle(lst/dict)#隨機打亂序列,返回值為None,直接修改序列,不能操作元組和集合,操作字典有時會報錯
- randrange(a,b,n)#指定區間內的整數,取值範圍[a,b),不包含b,a,b可以是浮點數,但只能是n.0,a必須小於b
- uniform(a,b)#指定區間內的數值,可以是複數,取值包含a也包含b,a和b可以相等,a可以小於b
a = rd.random()
print(a)
import math
print(math.floor(rd.random()*10)/10)
複製程式碼
0.7688124235586536
0.3
複製程式碼
a = rd.choice([1,2,4,5,7])
print(a)
dict1 = {0:3,1:4,2:5}
print(rd.choice(dict1))
dict1 = {'a':3,'b':4,'c':5}
print(rd.choice(dict1))
dict1 = {1:3,6:4,7:5}
print(rd.choice(dict1))
'''random.py中對choice方法的實現如下,先得到0- (len(seq)-1)之間的整數,然後將獲取到的整數作為下標去訪問序列中的value,找不到就報錯了
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence') from None
return seq[i]
'''
複製程式碼
2
5
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-3-f321c81453d3> in <module>()
7
8 dict1 = {'a':3,'b':4,'c':5}#不會報錯,長度為n的元素,key為[0-n-1]的之間的整數不會報錯,為其他值可能報錯,全為字串一定報錯
----> 9 print(rd.choice(dict1))
D:\ProgramData\Anaconda3\lib\random.py in choice(self, seq)
256 except ValueError:
257 raise IndexError('Cannot choose from an empty sequence') from None
--> 258 return seq[i]
259
260 def shuffle(self, x, random=None):
KeyError: 2
複製程式碼
dict1 = {'a':3,'b':4,'c':5}
keys = list(dict1.keys())
values = list(dict1.values())
print(rd.choice(keys))
print(rd.choice(values))
複製程式碼
b
5
複製程式碼
a = [1,2,3,4,5,6]
rd.shuffle(a)
print(a)
''' 和choice相同都是通過下標訪問的,所以同樣會報錯
def shuffle(self, x, random=None):
"""Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.
"""
if random is None:
randbelow = self._randbelow
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = randbelow(i+1)
x[i], x[j] = x[j], x[i]
else:
_int = int
for i in reversed(range(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = _int(random() * (i+1))
x[i], x[j] = x[j], x[i]
'''
複製程式碼
[3, 6, 2, 1, 4, 5]
複製程式碼
a = rd.randrange(1,5,2)
print(a)
複製程式碼
3
複製程式碼
a = rd.uniform(1,5)
print(a)
'''
def uniform(self, a, b):
"Get a random number in the range [a, b) or [a, b] depending on rounding."
return a + (b-a) * self.random()
'''
a = rd.uniform(1+5j,1+1j)
print(a)
a = rd.uniform(1+5j,1+5j)
print(a)
複製程式碼
4.328510673589862
(1+2.2475224962081475j)
(1+5j)
複製程式碼