我一次只需要從串列中選擇一定數量的(隨機)關鍵字,而不是像現在這樣使用所有鍵進行 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))
uj5u.com熱心網友回復:
如果要從串列中隨機選擇多個專案,可以使用random.choices(). 在這個例子中,它將選擇 4 個隨機關鍵字:
import random
keywords = ["Televisori", "Notebook", "Tablet", "Apple", "Samsung", "Smartwatch", "Auricolari Bluetooth", "Fotocamera",
"Videocamera"]
random_keywords = random.choices(keywords, k=4)
uj5u.com熱心網友回復:
IIUC,您可以使用random.sample任何range(1,len(population))您喜歡的值:
(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']
uj5u.com熱心網友回復:
您可以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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/342464.html
上一篇:處理資料集上的空值
