首页 > 编程知识 正文

python 从列表中随机选择,python从列表中随机取一个元素

时间:2023-05-03 20:24:49 阅读:279784 作者:85

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列表中随机选择

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。