目录

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

目录

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

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']
>>>

翻译自:

python列表中随机选择