I need to select only a certain number of (random) keywords from the list at a time and not make an API call with all the keys as is the case now. How can I proceed?
# 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))
CodePudding user response:
If you want to select a number of random items from the list, you can use random.choices()
. In this example, it will select 4 random keywords:
import random
keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera",
"Videocamera"]
random_keywords = random.choices(keywords, k=4)
CodePudding user response:
IIUC, You can use random.sample
with any value in range(1,len(population))
you like:
(random.sample Chooses k unique random elements from a population)
>>> 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']
CodePudding user response:
You can get n
random elements from the list like this:
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)