日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發(fā)布時間:2023/12/20 python 55 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python random函数sample_Python random.sample()用法及代码示例 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

用法: random.sample(sequence, k)

參數(shù):

sequence:可以是列表,元組,字符串或集合。

k:一個整數(shù)值,它指定樣本的長度。

返回:k長度從序列中選擇的新元素列表。

代碼1:sample()函數(shù)的簡單實現(xiàn)。

# 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()函數(shù)的基本用法。

# 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:引發(fā)異常

如果樣本大小(即k)大于序列大小,則會引發(fā)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

總結(jié)

以上是生活随笔為你收集整理的python random函数sample_Python random.sample()用法及代码示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。