Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสุ่มเลือกสมาชิกจากลิสต์ใน Python (random.choice)

โมดูล random ใน standard library มี generator แบบ pseudo-random based on Mersenne Twister algorithm

วิธีที่ 1: random.choice() (แนะนำ)

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

choice() เลือกสมาชิกสุ่มจาก sequence (string, list, tuple) ได้โดยตรง

วิธีที่ 2: random.randrange() + indexing

>> from random import randrange
>>> lst = [1, 2, 3, 4, 5]
>>> index = randrange(len(lst))  # 0 ถึง len-1
>>> lst[index]
4
>>> index = randrange(len(lst))
>>> lst[index]
3

ฟังก์ชันสุ่มอื่นๆ ที่น่าสนใจ

  • random.randint(a, b) - จำนวนเต็มสุ่ม a ถึง b (รวม)
  • random.random() - float 0.0-1.0
  • random.uniform(a, b) - float a ถึง b
  • random.sample(population, k) - เลือก k รายการ ไม่ซ้ำกัน
  • random.shuffle(list) - สลับลำดับลิสต์ in-place

คำเตือน: ไม่เหมาะสำหรับการเข้ารหัส/ความปลอดภัย ใช้โมดูล secrets แทน