當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python random.sample()用法及代碼示例


sample()是Python中隨機模塊的內置函數,可返回從序列中選擇的項目的特定長度列表,即列表,元組,字符串或集合。用於隨機抽樣而無需更換。

用法: random.sample(sequence, k)

參數:
sequence:可以是列表,元組,字符串或集合。
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 = "GeeksforGeeks"
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)大於序列大小,則會引發ValueError。

# 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:\Users\user\AppData\Local\Programs\Python\Python36\lib\random.py", line 317, in sample
    raise ValueError("Sample larger than population or is negative")
ValueError:Sample larger than population or is negative


相關用法


注:本文由純淨天空篩選整理自AnkitRai01大神的英文原創作品 Python | random.sample() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。