When we need to generate random numbers or randomly select elements from a sequence, we can use Python's built-in random library. Here is an annotated example that demonstrates how to use the random library:
# 导入 random 库 import random # 生成一个 0 到 1 之间的随机小数 random_float = random.random() print(random_float) # 生成一个指定范围内的随机整数(包括端点) random_int = random.randint(1, 10) print(random_int) # 从列表中随机选择一个元素 my_list = ["apple", "banana", "cherry"] random_element = random.choice(my_list) print(random_element) # 打乱列表的顺序 my_list2 = ["apple", "banana", "cherry"] random.shuffle(my_list2) print(my_list2) # 从指定概率分布中随机选择一个元素(这里是一个二项分布) random_binomial = random.choices([0, 1], weights=[0.7, 0.3]) print(random_binomial) # 从指定序列中随机选择多个元素(这里选择两个元素) my_list3 = ["apple", "banana", "cherry", "date"] random_sample = random.sample(my_list3, k=2) print(random_sample)
The output may look like this:
0.6253281864829788
5
banana
['banana', 'cherry', 'apple']
[1]
['banana', 'date']
The above code provides common random operations, But that's not all. The random library also provides many APIs that can be used flexibly according to needs.
The above is the detailed content of How to use demo of python random library. For more information, please follow other related articles on the PHP Chinese website!