【问题标题】:Unsure how to select one random output from this list in python不确定如何在 python 中从此列表中选择一个随机输出
【发布时间】:2018-08-30 06:01:27
【问题描述】:

我想在调用音乐功能时从该列表中随机选择一个 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")

【问题讨论】:

    标签: python list telegram-bot chatbot python-telegram-bot


    【解决方案1】:

    使用这个

    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?

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

        【解决方案3】:

        使用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)
        

        【讨论】:

          【解决方案4】:

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

          第二步:使用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))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-09-23
            • 2017-04-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多