Home >Backend Development >Python Tutorial >Introduction to the sample function in python

Introduction to the sample function in python

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2024-01-27 13:42:561577browse

The random.sample function in Python is used to randomly extract elements of a specified length from a specified sequence and return a new list. The syntax of the function is "random.sample(population, k)", where population is An iterable sequence, which can be a list, tuple, set, etc., and k is the number of elements to be extracted.

Introduction to the sample function in python

In Python, the random.sample function is used to randomly extract elements of a specified length from a specified sequence and return a new list. The syntax of this function is as follows:

random.sample(population, k)

Among them, population is an iterable sequence, which can be a list, tuple, set, etc., and k is the number of elements to be extracted.

For example, assuming there is a list [1, 2, 3, 4, 5], we can use the random.sample function to randomly select a part of the elements:

import random
seq = [1, 2, 3, 4, 5]
sampled = random.sample(seq, 3)
print(sampled)  # 可能的输出:[3, 1, 4]

In this example, random.sample randomly selects 3 elements from the seq list, and the returned sampled list contains these 3 randomly selected elements.

It should be noted that the random.sample function does not change the original sequence, but returns a new list containing extracted elements. In addition, if you try to extract elements from an empty sequence, or if the number of elements required to be extracted exceeds the length of the sequence, a ValueError exception will be triggered.

In short, the random.sample function is a convenient tool that can play a role in scenarios that require random extraction of elements, such as data processing, simulation experiments, etc. It is widely used.

The above is the detailed content of Introduction to the sample function in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn