Pythonランダムchoices()メソッド
例
14項目のリストを返します。
リストには、指定されたリストからランダムに選択された値が含まれている必要があり、他の2つよりも「リンゴ」を選択する可能性が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 |