Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chọn ngẫu nhiên phần tử từ list trong Python (random.choice)

Module random cung cấp choice() để chọn ngẫu nhiên 1 phần tử từ sequence (list, tuple, string).

Ví dụ cơ bản

from random import choice
lst = [1, 2, 3, 4, 5]
print(choice(lst))  # 4
print(choice(lst))  # 5
print(choice(lst))  # 3

Cách thay thế: randrange + index

from random import randrange
lst = [1, 2, 3, 4, 5]
index = randrange(len(lst))
print(lst[index])

Chọn nhiều phần tử

  • random.choices(lst, k=3) — có thể trùng (Python 3.6+).
  • random.sample(lst, k=3) — không trùng, sampling without replacement.
import random
print(random.choices([1,2,3,4,5], k=3))  # ví dụ: [2, 2, 5]
print(random.sample([1,2,3,4,5], 3))     # ví dụ: [4, 1, 3]

Lưu ý: Dùng secrets.choice() cho mục đích bảo mật/cryptography.