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'] >>>翻譯自: https://www.includehelp.com/python/how-to-randomly-select-an-item-from-a-list.aspx
python列表中隨機選擇
總結
以上是生活随笔為你收集整理的python列表中随机选择_如何在Python中从列表中随机选择一个项目?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java类类getClassLoader
- 下一篇: Java中的Switch都支持Strin