Pilihan Acak Python () Metode
Contoh
Kembalikan daftar dengan 14 item.
Daftar tersebut harus berisi pilihan nilai secara acak dari daftar yang ditentukan, dan harus ada kemungkinan 10 kali lebih tinggi untuk memilih "apel" daripada dua lainnya:
import random
mylist = ["apple", "banana", "cherry"]
print(random.choices(mylist,
weights = [10, 1, 1], k = 14))
Definisi dan Penggunaan
Metode choices()
mengembalikan daftar dengan elemen yang dipilih secara acak dari urutan yang ditentukan.
Anda dapat menimbang kemungkinan setiap hasil dengan parameter bobot atau parameter cum_weights.
Urutan dapat berupa string, rentang, daftar, tupel, atau jenis urutan lainnya.
Sintaksis
random.choices(sequence, weights=None, cum_weights=None, k=1)
Nilai Parameter
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 |