【问题标题】:Select n keywords from list从列表中选择 n 个关键字
【发布时间】:2021-12-15 13:58:30
【问题描述】:

我一次只需要从列表中选择一定数量的(随机)关键字,而不是像现在这样使用所有键进行 API 调用。 我该如何继续?

    # Search keywords definition
keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera",
            "Videocamera"]

# run bot function
def run_bot(bot, keywords):
    # shuffling keywords list
    random.shuffle(keywords)

    # start loop
    while True:
        try:
            items_full = []

            # iterate over keywords
            for el in keywords:
                # iterate over pages
                for i in range(1, 10):

                    items = search_items(el, CATEGORY, item_page=i)

                    # api time limit for another http request is 1 second
                    time.sleep(1)

                    items_full.append(items)

            # concatenate all results
            items_full = list(chain(*items_full))

【问题讨论】:

    标签: python list random


    【解决方案1】:

    如果你想从列表中随机选择一些项目,你可以使用random.choices()。在本例中,它将随机选择 4 个关键字:

    import random
    keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera",
                "Videocamera"]
    random_keywords = random.choices(keywords, k=4)
    

    【讨论】:

      【解决方案2】:

      IIUC,您可以在 range(1,len(population)) 中使用 random.sample 任意值:

      (random.sample 从总体中选择 k 个唯一的随机元素)

      >>> import random
      >>> keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera","Videocamera"]
      
      >>> random.sample(keywords,5)
      ['Fotocamera', 'Videocamera', 'Notebook', 'Televisori', 'Samsung']
      
      >>> random.sample(keywords,2)
      ['Televisori', 'Smartwatch']
      

      【讨论】:

        【解决方案3】:

        您可以像这样从列表中获取n 随机元素:

        import random
        keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera",
                    "Videocamera"]
        
        random.shuffle(keywords)
        n = 10
        new_list = keywords[:n]
        print(new_list)
        

        【讨论】:

          猜你喜欢
          • 2011-11-25
          • 1970-01-01
          • 1970-01-01
          • 2016-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多