欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python random函数sample_Python random.sample()用法及代码示例

发布时间:2023/12/20 python 59 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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: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

总结

以上是生活随笔为你收集整理的python random函数sample_Python random.sample()用法及代码示例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。