python学习笔记----random

import random
import string

# 随机整数:
print random.randint(1,50)

>>> print(random.randint(1,50))
16
>>> print(random.randint(1,50))
31


# 随机选取0到100间的偶数:
print random.randrange(0, 101, 2)

>>> print(random.randrange(0, 101, 2))
42
>>> print(random.randrange(0, 101, 2))
80
>>> print(random.randrange(0, 101, 2))
14


# 随机浮点数:
print random.random()#0-1的随机小数

>>> print( random.random())
0.2238481522116863
>>> print( random.random())
0.9447280929024309

print random.uniform(1, 10)#指定范围的随机小数

>>> print (random.uniform(1, 10))
2.701334819048406
>>> print (random.uniform(1, 10))
5.746240873002879


# 随机字符:
print random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()')>>> print( random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()'))d>>> print( random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()'))p

# 多个字符中生成指定数量的随机字符:
print random.sample('zyxwvutsrqponmlkjihgfedcba',5)

>>> print( random.sample('zyxwvutsrqponmlkjihgfedcba',5))
['r', 'z', 'y', 'c', 'l']
>>> print( random.sample('zyxwvutsrqponmlkjihgfedcba',5))
['l', 'a', 'y', 'i', 'q']


# 从a-zA-Z0-9生成指定数量的随机字符:
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print ran_str

>>> ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))

>>> print (ran_str)
28vyNHqA

>>> import string
>>> string.ascii_letters#生成所有的大小写字母
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits#生成所有的数字
'0123456789'
>>> "".join(random.sample(string.ascii_letters+string.digits,8))

'QmFNB7wC'

>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__built
ins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__packag
e__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_u
ppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctua
tion', 'whitespace']
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase#所有的小写字母
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase#生成所有的大写字母
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

# 多个字符中选取指定数量的字符组成新字符串:
print( ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5)))



# 随机选取字符串:
print random.choice(['剪刀', '石头', '布'])



# 打乱排序
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print random.shuffle(items)

>>> s=[1,2,3,4,5,6]
>>> random.shuffle(s)
>>> s
[3, 1, 4, 5, 6, 2]

 
上一篇:Xutils3的使用


下一篇:第25课 可变参数模板(6)_function_traits和ScopeGuard的实现