pythonでリストから重複なしでランダムに複数の要素を取得する方法/random.sample関数の使い方

lab IT

random.sample関数はリストから指定した個数の項目の入ったリストを作成する関数ですが、項目が重複しないという特徴があります。

スポンサーリンク

random.sample関数

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

コメント

This website stores cookies on your computer. These cookies are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to to opt-out of any future tracking, a cookie will be setup in your browser to remember this choice for one year.

Accept or Deny