Python Basic

Random python

Function Description
randrange()Returns a random number between the given range
randint()Returns a random number between the given range
choice()Returns a random element from the given sequence
choices()Returns a list with a random selection from the given sequence
shuffle()Takes a sequence and returns the sequence in a random order
sample()Returns a given sample of a sequence
random()Returns a random float number between 0 and 1

Ví dụ randint

from random import randint
randint(0, 3)

Kết quả trả về số trong khoảng [0, 3]

Ví dụ choices

from random import choices
a = [1, 3, 7, 5]
choices(a, k = 10)

Kết quả trả về 1 list có 10 phần tử chứa 1 trong các giá trị của list a

Ví dụ sample

from random import sample a = [1, 3, 7, 5] rample(a, 3)

Kết quả trả về 3 phần tử trong số các phần tử của list a, không lặp lại