python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python中random.choices函数

Python中的random.choices函数用法详解

作者:Yorlen_Zhang

这篇文章主要给大家介绍了关于Python中random.choices函数用法的相关资料,random.random() 的功能是随机返回一个 0-1范围内的浮点数,文中通过代码介绍的非常详细,需要的朋友可以参考下

1. 什么是random.choices函数?

random.choices是Python标准库中random模块提供的一个函数,用于从给定的序列中随机选择一个值。这个函数可以用于实现随机抽样、按照概率进行选择等功能。

random.choices(population, weights=None, *, cum_weights=None, k=1)函数的参数解释如下:

2. random.choices函数的用法示例

示例1:从列表中随机选择一个元素

import random

fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
chosen_fruit = random.choices(fruits)
print(chosen_fruit)

运行结果

['grape'] 

示例2:按照概率从列表中随机选择一个元素

import random

fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
weights = [0.1, 0.2, 0.3, 0.2, 0.2]
chosen_fruit = random.choices(fruits, weights=weights)
print(chosen_fruit)

运行结果

['orange'] 

示例3:选择多个元素

import random

fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
chosen_fruits = random.choices(fruits, k=3)
print(chosen_fruits)

运行结果

['banana', 'apple', 'watermelon'] 

示例4:利用cum_weights参数选择元素 

import random

fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
cum_weights = [0.1, 0.4, 0.7, 0.9, 1.0]
chosen_fruit = random.choices(fruits, cum_weights=cum_weights)
print(chosen_fruit)

运行结果

['grape'] 

示例5:选择多个元素并计算选择的次数

import random

fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
chosen_fruits = random.choices(fruits, k=1000)
fruit_counts = {}

for fruit in chosen_fruits:
    if fruit in fruit_counts:
        fruit_counts[fruit] += 1
    else:
        fruit_counts[fruit] = 1

print(fruit_counts)

 运行结果

{'orange': 334, 'grape': 192, 'apple': 203, 'watermelon': 152, 'banana': 119}

3. 总结

random.choices函数是Python中一个非常有用的函数,可以用于实现随机抽样、按照概率进行选择等功能。通过合理地使用参数,我们可以根据需求选择单个或多个元素,并可以对选择的元素进行计数等操作。

通过阅读本文,你应该对random.choices函数有了更深入的理解,并可以灵活地将其应用于自己的编程任务中。

4.特别提醒

random.choices 在 k>1 时,也就是选择的元素个数大于1时,元素是有可能重复的。要想得到一个不重复的随机数列,请自行编写方法。

附.可用场景

例如:2048这个游戏,每次随机的值都是2或者4,只有这两个值。下面是初始化2048棋盘的数据的一个函数,里面可以看到咱们使用的就是random.choice来获取数组中的随机两个值的。

def init():
    """
    初始化操作
    :return:
    """
    # 随机生成两个2或4并防止到棋盘中
    for i in range(2):
        while True:
            # 棋盘位置
            row = random.randint(0, 3)
            col = random.randint(0, 3)
            if data[row][col] == 0:
                # 在数组重随机抽取2或4·棋盘数字
                data[row][col] = random.choice([2, 4])
                break

注意内容 

注:

1、random.choice 函数不能直接用于选择字典中的随机键值对,因为该函数是用于从序列中选择随机元素的。如果要从字典中选择随机键值对,可以使用 random.choice(list(dictionary.items())) 的方法来实现。

2、random.choice 函数不能用于选择一个随机的布尔值。该函数的作用是从给定的序列中随机选择一个元素。在布尔值的情况下,你可以使用 random.choice([True, False]) 来随机选择一个布尔值。

总结

到此这篇关于Python中random.choices函数用法的文章就介绍到这了,更多相关Python中random.choices函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文