How do you use the sample function in Python?
In Python, the sample function is used to randomly select a specified number of elements from a given sequence. Its syntax is as follows:
Select k random elements from sequence.
In this case, the sequence refers to the chosen sequence, which can be a list, tuple, or string, with k representing the number of elements to be chosen.
Here is an example code using the sample function:
import random
# 从列表中随机选择两个元素
my_list = [1, 2, 3, 4, 5]
random_elements = random.sample(my_list, 2)
print(random_elements)
# 从字符串中随机选择三个字符
my_string = "Hello, World!"
random_chars = random.sample(my_string, 3)
print(random_chars)
Output:
[4, 1]
['l', 'o', 'l']
In the example above, the sample function selected two random elements from the list and three random characters from the string.