1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

引数を適当に回していたらエラーすることがあったため備忘録として書きました。

random.sample

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

シーケンスから重複なしでk個選ぶ。シーケンスはリスト, タプル, 文字列のいずれか。

random.sample([], k=0)    # []
random.sample([], k=1)    # エラー (ValueError)
random.sample([1], k=0)   # []
random.sample([1], k=1)   # [1]
random.sample([1], k=2)   # エラー (ValueError)
random.sample([1,2], k=0) # []
random.sample([1,2], k=1) # [1] or [2]
random.sample([1,2], k=2) # [1,2] or [2,1]
random.sample("abc", k=0) # []
random.sample("abc", k=1) # ['a'] or ['b'] or ['c']
random.sample("abc", k=2) # ['a','b'] or ['b','a'] or...
random.sample("abc", k=3) # ['a','b','c'] or ['b','a','c'] or... 
random.sample([1,2], counts=[1,2], k=2) # =random.sample([1,2,2], k=2)

random.choices

population から重複ありで選んだ要素からなる大きさ k のリストを返します。population が空の場合 IndexError を送出します。

シーケンスから重複なしでk個選ぶ。シーケンスはリスト, タプル, 文字列のいずれか。

random.choices([], k=0)    # []
random.choices([], k=1)    # エラー (IndexError)
random.choices([1], k=0)   # []
random.choices([1], k=1)   # [1]
random.choices([1], k=2)   # [1,1]
random.choices([1,2], k=0) # []
random.choices([1,2], k=1) # [1] or [2]
random.choices([1,2], k=2) # [1,1] or [1,2] or [2,1] or [2,2]
random.choices("abc", k=0) # []
random.choices("abc", k=1) # ['a'] or ['b'] or ['c']
random.choices("abc", k=2) # ['a','a'] or ['a','b'] or ['b','a'] or...
random.choices("abc", k=3) # ['a','a','a'] or ['b','a','a'] or...
random.choices("abc", weights=[1,0,0], k=3) # ['a','a','a']
random.choices("abc", weights=[0,0,0], k=3) # エラー (ValueError)

(Python 3.9.6)

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?