日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

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

發(fā)布時(shí)間:2025/3/11 49 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python列表中随机选择_如何在Python中从列表中随机选择一个项目? 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。