パイソン |ランダムサンプル()関数

サンプル() は組み込み関数です ランダムモジュール Python では、シーケンス (リスト、タプル、文字列、セットなど) から選択された項目の特定の長さのリストを返します。非置換のランダムサンプリングに使用されます。

構文: ランダム.サンプル(シーケンス, k)

パラメーター:
順序 : リスト、タプル、文字列、またはセットを指定できます。
k : 整数値。サンプルの長さを指定します。

戻り値: k 長さのシーケンスから選択された要素の新しいリスト。

コード #1: Sample() 関数の単純な実装。




# Python3 program to demonstrate> # the use of sample() function .> > # import random> from> random> import> sample> > # Prints list of random items of given length> list1> => [> 1> ,> 2> ,> 3> ,> 4> ,> 5> ]> > print> (sample(list1,> 3> ))>

出力:

[2, 3, 5] 


コード #2: Sample() 関数の基本的な使い方。




# Python3 program to demonstrate> # the use of sample() function .> > # import random> import> random> > > # Prints list of random items of> # length 3 from the given list.> list1> => [> 1> ,> 2> ,> 3> ,> 4> ,> 5> ,> 6> ]> print> (> 'With list:'> , random.sample(list1,> 3> ))> > # Prints list of random items of> # length 4 from the given string.> string> => 'techcodeview.com'> print> (> 'With string:'> , random.sample(string,> 4> ))> > # Prints list of random items of> # length 4 from the given tuple.> tuple1> => (> 'ankit'> ,> 'geeks'> ,> 'computer'> ,> 'science'> ,> > 'portal'> ,> 'scientist'> ,> 'btech'> )> print> (> 'With tuple:'> , random.sample(tuple1,> 4> ))> > > # Prints list of random items of> # length 3 from the given set.> set1> => {> 'a'> ,> 'b'> ,> 'c'> ,> 'd'> ,> 'e'> }> print> (> 'With set:'> , random.sample(set1,> 3> ))>

出力:

With list: [3, 1, 2] With string: ['e', 'f', 'G', 'G'] With tuple: ['ankit', 'portal', 'geeks', 'computer'] With set: ['b', 'd', 'c'] 

注記: ランダムなアイテムを返すため、出力は毎回異なります。

コード #3: 例外を発生させる

サンプルサイズ、つまり k がシーケンスサイズより大きい場合、 値エラー 上げられる。




# Python3 program to demonstrate the> # error of sample() function.> import> random> > list1> => [> 1> ,> 2> ,> 3> ,> 4> ]> > # exception raised> print> (random.sample(list1,> 5> ))>

出力:

 Traceback (most recent call last): File 'C:/Users/user/AppData/Local/Programs/Python/Python36/all_prgm/geeks_article/sample_method_article.py', line 8, in print(random.sample(list1, 5)) File 'C:UsersuserAppDataLocalProgramsPythonPython36lib
andom.py', line 317, in sample raise ValueError('Sample larger than population or is negative') ValueError: Sample larger than population or is negative