Python สุ่มตัวเลือก ()วิธีการ
ตัวอย่าง
กลับรายการที่มี 14 รายการ
รายการควรประกอบด้วยการเลือกค่าแบบสุ่มจากรายการที่ระบุ และควรมีความเป็นไปได้มากกว่า 10 เท่าในการเลือก "แอปเปิ้ล" มากกว่าสองค่าอื่น:
import random
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist,
weights = [10, 1, 1], k = 14))
ความหมายและการใช้งาน
เมธอด จะchoices()
ส่งคืนรายการที่มีองค์ประกอบที่สุ่มเลือกจากลำดับที่ระบุ
คุณสามารถชั่งน้ำหนักความเป็นไปได้ของผลลัพธ์แต่ละรายการด้วยพารามิเตอร์ weights หรือพารามิเตอร์ cum_weights
ลำดับอาจเป็นสตริง ช่วง รายการ ทูเพิล หรือลำดับประเภทอื่นๆ
ไวยากรณ์
random.choices(sequence, weights=None, cum_weights=None, k=1)
ค่าพารามิเตอร์
Parameter | Description |
---|---|
sequence | Required. A sequence like a list, a tuple, a range of numbers etc. |
weights | Optional. A list were you can weigh the possibility for each value. Default None |
cum_weights | Optional. A list were you can weigh the possibility for each value, only
this time the possibility is accumulated. Example: normal weights list: [2, 1, 1] is the same as this cum_weights list; [2, 3, 4]. Default None |
k | Optional. An integer defining the length of the returned list |