python 从列表中随机选择_python列表中随机选择_如何在Python中从列表中随机选择一个项目?...

本文介绍了Python的random模块中的choice()方法,用于从列表或其他序列中随机选取单个或多个元素。通过示例代码展示了如何随机选择一个列表项以及如何使用choices()方法来选取多个不重复的随机项。此功能在编程中常用于模拟、测试等场景。
摘要由CSDN通过智能技术生成

python列表中随机选择

Python random module provides an inbuilt method choice() has an ability to select a random item from the list and other sequences. Using the choice() method, either a single random item can be chosen or multiple items. The below set of examples illustrate the behavior of choice() method.

Python 随机模块提供了一种内置方法choice() ,可以从列表和其他序列中选择一个随机项。 使用choice()方法,可以选择一个随机项目或多个项目。 下面的示例集说明了choice()方法的行为。

Syntax:

句法:

random.choice(sequence)

Here, sequence can be a list, set, dictionary, string or tuple.

在这里, 序列可以是列表,集合,字典,字符串或元组。

Example 1: Choose a single item randomly from the list

示例1:从列表中随机选择一个项目

>>> import random

>>> test_list = ['include_help', 'wikipedia', 'google']

>>> print(random.choice(test_list))

wikipedia

>>> print(random.choice(test_list))

google

>>> print(random.choice(test_list))

wikipedia

>>>

Example 2: Choose multiple items randomly from the list

示例2:从列表中随机选择多个项目

In order to select multiple items from list, random module provides a method called choices.

为了从列表中选择多个项目,随机模块提供了一种称为choices的方法。

>>> import random

>>> print(random.choices(test_list, k=2))

['wikipedia', 'include_help']

>>> print(random.choices(test_list, k=1))

['google']

>>> print(random.choices(test_list, k=3))

['google', 'google', 'google']

>>>

翻译自: https://www.includehelp.com/python/how-to-randomly-select-an-item-from-a-list.aspx

python列表中随机选择

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值