python之random用法
random.choice(sequence) 从序列中获取一个随机元素,参数sequence表示一个有序类型,泛指一系列类型,如list,tuple,字符串。
import random list_1 = ['python','java','c'] str_1 = "i love python" tuple_1 = (1,2,'kai') print(random.choice(list_1),type(random.choice(list_1))) #java print(random.choice(str_1),type(random.choice(str_1))) #e print(random.choice(tuple_1),type(random.choice(tuple_1))) #kai
# 随机选取字符串: import random a=random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] ) print(a,type(a))
random.sample(sequence,k) 从指定序列中随机获取指定长度的片段。sample函数不会修改原有的序列。
import random list_1 = ['one','two','three','four'] slice = random.sample(list_1,2) print(list_1) # ['one', 'two', 'three', 'four'] print(slice) # ['two', 'three']
import random #随机的选取n个字符 print(random.sample('abcdefghijk',3),type(random.sample('abcdefghijk',3))) #随机的选取一个字符 print(random.choice('af/fse.faek``fs'),type(random.choice('af/fse.faek``fs')))