不确定如何 select 从 python 中的这个列表中随机输出一个

Unsure how to select one random output from this list in python

我想在调用音乐功能时 select 从该列表中随机 update.message 一个。我假设我应该将所有链接存储在 update.message 之外,这样它就不会在音乐

调用时发送所有 3 个链接
def music(bot, update):

    update.message.reply_text("https://www.youtube.com/watch?v=XErrOJGzKv8")
    update.message.reply_text("https://www.youtube.com/watch?v=hHW1oY26kxQ")
    update.message.reply_text("https://www.youtube.com/watch?v=RmHg6BP5D8g")

random 擅长随机选择。

import random
playlist = ['https://www.youtube.com/watch?v=XErrOJGzKv8','https://www.youtube.com/watch?v=hHW1oY26kxQ', 'https://www.youtube.com/watch?v=RmHg6BP5D8g']

def music(bot, update):
    update.message.reply_text(random.choice(playlist)) # random.choice() chooses a random item from a list

使用random.choice(seq)

import random

def music (bot, update):

    list_of_urls = ["www.your-urls.com", "www.your-urls2.com"]
    random_url = random.choice(list_of_urls)

    update.message.reply_text(random_url)

第一步:将您的值存储在列表中。

第二步:只需使用random.choice()

import random

my_links = [
    "https://www.youtube.com/watch?v=XErrOJGzKv8",
    "https://www.youtube.com/watch?v=hHW1oY26kxQ",
    "https://www.youtube.com/watch?v=RmHg6BP5D8g"
]


def music(bot, update):
    update.message.reply_text(random.choice(my_links))

使用这个

import random
foo=['link1','link2','link3']
random_link=random.choice(foo)
#call your function here using random_link

也参考这个问题How to randomly select an item from a list?