Python random.sample()

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:样本()函数的基本使用。

# 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程