我正在學習 python,并嘗試撰寫一個代碼,該代碼將呈現給用戶從池中隨機選擇的單詞,并要求他為這個單詞撰寫翻譯。如果用戶正確翻譯了單詞,則應從池中洗掉該單詞。
感謝您的任何幫助。
dic = {
"key1": "val1",
"key2": "val2",
"key3": "val3"
}
import random
for keys, values in dict(dic).items():
a = []
a.append(random.choice(list(dic)))
translation = input(f"what is the translation for {a}")
translation.replace("'", "")
if a[0] == translation:
del dic[keys]
這是我寫的代碼,但即使條件發生,單詞也不會從池中洗掉。
uj5u.com熱心網友回復:
正如 BrokenBenchmark 所說,不要洗掉回圈中的元素!!!
復制密鑰,并從原始字典中洗掉。
這是您的代碼的更正版本:
dic = {
"key1": "val1",
"key2": "val2",
"key3": "val3"
}
import random
keys = list(dic.copy())
random.shuffle(keys)
for key in keys:
translation = input(f"what is the translation for {key}: ")
translation.replace("'", "")
if dic[key] == translation:
del dic[key]
print(dic)
uj5u.com熱心網友回復:
不要在迭代資料結構時從資料結構中洗掉專案。
在這種情況下,請注意您正在從字典中洗掉,因為您不想隨機選擇兩次相同的單詞。一種更好的方法(在迭代時不需要洗掉元素)是將字典轉換為元組串列,打亂該串列,然后迭代該串列。這讓我們可以選擇一個隨機生成的單詞,而不必擔心選擇兩次相同的單詞。
這是一個代碼片段,展示了如何實作這一點:
import random
words = [('key1', 'val1'), ('key2', 'val2'), ('key3', 'val3')]
random.shuffle(words)
for word, translated_word in words:
user_translation = input(f"what is the translation for {word}?")
# Remember that .replace() does not modify the original string,
# so we need to explicitly assign its result!
user_translation = user_translation.replace("'", "")
if user_translation == translated_word:
print('Correct!')
else:
print('Incorrect.')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450409.html
上一篇:PHP從陣列中寫入一個數字
