random.sample関数はリストから指定した個数の項目の入ったリストを作成する関数ですが、項目が重複しないという特徴があります。
random.sample関数
![python random sample1](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample1.png)
sample関数を使うには、まずrandomモジュールをimportし、
#python
import random
list = [1,2,3,4,5]
print(random.sample(list,3))
random.sample関数の引数に項目を抜き出したいリストと、抜き出す項目の数を指定します。
![python random sample2](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample2.png)
実行結果がこちら。
![python random sample3](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample3.png)
sampleで抜き出したリストの項目は重複しません。項目数と抜き出す数が一致する場合、すべての項目が一度ずつ取得されます。
![python random sample4](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample4.png)
リストの項目より多い数を抜き出そうとするとエラーになります。
![python random sample5](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample5.png)
タプルにも使用できますが、
![python random sample6](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample6.png)
辞書だとエラーになるようです。
![python random sample7](https://sunagitsune.com/wp-content/uploads/2022/11/python-random-sample7.png)
抜き出す項目数が1、0の場合もリストが取得されます(0の場合空のリスト)。
![](https://sunagitsune.com/wp-content/uploads/2022/05/laptop-g2651bd324_1280-160x90.png)
Python操作方法、関数・メソッドリファレンス
使用用途別にまとめたPythonリファレンスページです。
初期準備、基本概念
ダウンロード、インストール、起動
ShellとEditor、保存、実行
保存したPythonの起動
コメント、docstring、行またぎ
コメント、...
コメント