Python隨機(jī)數(shù)/Python隨機(jī)字符串的相關(guān)代碼解析
以下的文章是通過Python隨機(jī)數(shù)與Python隨機(jī)字符串在實(shí)際應(yīng)用中的代碼的形式來(lái)介紹Python隨機(jī)數(shù)與Python隨機(jī)字符串的實(shí)際應(yīng)用的相關(guān)介紹,以下是文章的具體介紹,下面讓我們一起分享吧!
Python隨機(jī)數(shù)與隨機(jī)字符串
- >>> import random
- >>> random.randint(0,99)
- 21
隨機(jī)選取0到100間的偶數(shù):
- >>> import random
- >>> random.randrange(0, 101, 2)
- 42
隨機(jī)浮點(diǎn)數(shù):
- >>> import random
- >>> random.random()
- 0.85415370477785668
- >>> random.uniform(1, 10)
- 5.4221167969800881
隨機(jī)字符:
- >>> import random
- >>> random.choice('abcdefg&#%^*f')
- 'd'
多個(gè)字符中選取特定數(shù)量的字符:
- >>> import random
- random.sample('abcdefghij',3)
- ['a', 'd', 'b']
多個(gè)字符中選取特定數(shù)量的Python隨機(jī)字符字符串:
- >>> import random
- >>> import string
- >>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
- eplace(" ","")
- 'fih'
隨機(jī)選取字符串:
- >>> import random
- >>> 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]
以上的文章就是對(duì)Python隨機(jī)數(shù)與Python隨機(jī)字符串的實(shí)際應(yīng)用代碼的介紹。
【編輯推薦】