這是我想要做的:
從串列中隨機選擇一個詞
要求一個詞的用戶將其替換為
列印出替換單詞的串列
所以我完成了隨機單詞選擇器部分,但我不知道如何用輸入替換單詞。我以為我可以使用 .replace() 函式,但它是一個串列。這是代碼:
import random
all_lists = ['beans','peaches','yogurt','eggs','pizza']
for x in all_lists:
print(x)
appending_list = input("Would you like to replace a word? Yes or No?")
if appending_list == ("Yes"):
random = random.choice(all_lists) #this picks the random word
replace_word = input("What would would you like to replace the word with?")
all_lists_replace = all_lists.replace(random, replace_word)
print(all_lists_replace)
if appending_list == ("No"):
exit()
uj5u.com熱心網友回復:
使用索引
from random import randrange
all_lists = ['beans','peaches','yogurt','eggs','pizza']
for x in all_lists:
print(x)
appending_list = input("Would you like to replace a word? Yes or No?")
if appending_list == ("Yes"):
idx = randrange(len(all_lists))
replace_word = input("What would would you like to replace the word with?")
all_lists[idx] = replace_word
print(all_lists)
uj5u.com熱心網友回復:
我建議您不要從串列中隨機選擇一個選項,而是選擇一個隨機索引。這樣,您可以通過簡單地將用戶的輸入分配給串列的該索引來替換串列的該元素。
appending_list = input("Would you like to replace a word? Yes or No?")
if appending_list == ("Yes"):
ix = random.randint(0, len(all_lists))
replace_word = all_lists[ix]
replacement = input(f"What should I replace {replace_word} with?")
all_lists[ix] = replacement
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360858.html
