python --- 随机数的使用(random包)

    科技2022-08-24  103

    1、choice(seq)

    seq 必须是有序的序列,返回序列中的一个随机项。

    from random import * c1 = choice([1, 2, 3, 4, 5]) c2 = choice((1, 2, 3, 4, 5)) c3 = choice(range(1, 11)) print(c1, c2, c3) #输出(3,3,5),是随机生成的

    2、randint(start, end)

    返回 [start, end] 之间的一个随机整数。注意是闭区间。

    from random import * r = randint(1, 5) print(r) #输出3

    3、random()

    返回一个 [0, 1) 的随机浮点数。注意有开区间。

    from random import * print(random()) #输出0.13233841003981506 print(round(random(), 3)) #输出0.407,即保留3位小数

    4、uniform(a, b)

    返回 [a, b] 之间的一个随机浮点数。注意是闭区间。

    from random import * print(uniform(10, 20)) #输出14.745955757615702 print(uniform(20, 10)) #输出19.555402510324406 print(uniform(30, 30)) #输出30.0

    5、randrange(start, end, step)

    返回[start,end)之间的一个随机整数。注意有开区间。 注意randrange VS randint

    from random import * print(randrange(0, 10, 2))

    6、sample(seq, number)

    从 seq 中随机取出 number 个元素,以列表的形式返回。 seq 有序或无序。

    from random import * print(sample({1, 2, 3, 4, 5}, 3)) #输出[3, 2, 1] print(sample('abcdefg', 3)) # 输出['f', 'c', 'd']

    7、shuffle(lt)

    将 lt (列表对象) 中的元素打乱。

    from random import * lt = ['a', 'b', 'c', 'd', 'e', 'f'] shuffle(lt) # 打乱列表中元素顺序 print(lt) #输出['c', 'd', 'e', 'a', 'f', 'b']
    Processed: 0.021, SQL: 9