python列表中随机选择_如何在Python中从列表中随机选择一个项目?
python列表中隨機(jī)選擇
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 隨機(jī)模塊提供了一種內(nèi)置方法choice() ,可以從列表和其他序列中選擇一個(gè)隨機(jī)項(xiàng)。 使用choice()方法,可以選擇一個(gè)隨機(jī)項(xiàng)目或多個(gè)項(xiàng)目。 下面的示例集說(shuō)明了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:從列表中隨機(jī)選擇一個(gè)項(xiàng)目
>>> 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:從列表中隨機(jī)選擇多個(gè)項(xiàng)目
In order to select multiple items from list, random module provides a method called choices.
為了從列表中選擇多個(gè)項(xiàng)目,隨機(jī)模塊提供了一種稱為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列表中隨機(jī)選擇
總結(jié)
以上是生活随笔為你收集整理的python列表中随机选择_如何在Python中从列表中随机选择一个项目?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java类类getClassLoader
- 下一篇: Python中的Dask数组