Python の random.sample() メソッドは何をしますか? 質問する

Python の random.sample() メソッドは何をしますか? 質問する

メソッドの使用方法とそれが何をもたらすかを知りたいですrandom.sample()。いつ使用すべきか、また使用例をいくつか教えてください。

ベストアンサー1

によるとドキュメンテーション:

ランダムサンプル(人口、k)

母集団シーケン​​スから選択された一意の要素の k 長さのリストを返します。置換なしのランダム サンプリングに使用されます。

基本的に、シーケンスから k 個の一意のランダム要素 (サンプル) を選択します。

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample範囲から直接操作することもできます:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

3.11 より前のバージョンでは、random.sampleセットでも動作します:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

ただし、random.sample任意の反復子では機能しません。

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence.  For dicts or sets, use sorted(d).

バージョン 3.9 では、次のcountsパラメータが追加されました:

繰り返し要素は、一度に 1 つずつ指定することも、オプションのキーワードのみの counts パラメータを使用して指定することもできます。たとえば、sample(['red', 'blue'], counts=[4, 2], k=5) は、sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5) と同じです。

おすすめ記事