python生成随机数
随机整数:
>>> import random
>>> random.randint(0,99)
50
随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
2
随机浮点数:
>>> import random
>>> random.random()
0.011508602165174242 #范围0-1.0
>>> random.uniform(1, 10)
2.8229556607576147
>>>
选择一个随机元素
>>> random.choice("abcde")
'b'
>>> random.choice("abcde")
'a'
将一个列表中的元素打乱
>>> p = ["Python","Ubuntu", "powerful","linuxidc", "and so on..."]
>>> random.shuffle(p)
>>> print (p)
['ubuntu', 'and so on...', 'Python', 'powerful', 'linuxidc']
从指定序列中随机获取指定长度片段
>>> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> a=random.sample(list,4)
>>> a
[6, 1, 7, 9]
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
随机字符:
>>> import random
>>> random.choice('linuxidc.com#abcdefg&q#%d^*f')
'q'
多个字符中选取特定数量的字符:
>>> import random
>>> random.sample('linuxidcabcdefgohij',3)
['o', 'u', 'l']
随机选取字符串:
>>> import random
>>> random.choice ( ['linuxidc', 'com', 'linuxmi', 'Oracle', 'ubuntu'] )
'oracle'
洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[2, 1, 5, 7, 3, 4, 6]