python 列表中随机选择_如何在Python 中从列表中随机选择⼀
个项⽬?
python列表中随机选择
Python random module random module provides an inbuilt method choice()choice() has an ability to select a random item from the list and other sequences. Using the choice()choice() method, either a single random item can be chosen or multiple items. The below set of examples illustrate the behavior of choice()choice() method.
Python 随机模块随机模块提供了⼀种内置⽅法choice()choice() ,可以从列表和其他序列中选择⼀个随机项。 使⽤choice()choice()⽅法,可以选择选择⼀个随机项⽬或多个项⽬。 下⾯的⽰例集说明了choice()choice()⽅法的⾏为。
Syntax:random翻译
句法:
Here, sequence can be a list, set, dictionary, string or tuple.
在这⾥, 序列可以是列表,集合,字典,字符串或元组。
Example 1: Choose a single item randomly from the list
⽰例1:从列表中随机选择⼀个项⽬
Example 2: Choose multiple items randomly from the list
⽰例2:从列表中随机选择多个项⽬
In order to select multiple items from list, random provides a method called choices.
为了从列表中选择多个项⽬,随机模块提供了⼀种称为choices的⽅法。
random.choice(sequence)
1
>>> import random 2
>>> test_list = ['include_help', 'wikipedia', 'google']3
>>> print(random.choice(test_list))4
wikipedia 5
>>> print(random.choice(test_list))6
google 7
>>> print(random.choice(test_list))8wikipedia 9>>>
1
>>> import random 2
>>> print(random.choices(test_list, k=2))3
['wikipedia', 'include_help']4
>>> print(random.choices(test_list, k=1))5
['google']6
>>> print(random.choices(test_list, k=3))7['google', 'google', 'google']8>>>
翻译⾃:
python列表中随机选择

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。