[英]Printing from a dictionary
對於學校的家庭作業,我們必須編寫代碼來執行以下操作:
編寫程序以測試您對動物科學名稱的了解。 您的程序應從animal.txt中讀取這些科學的動物名稱,然后要求用戶輸入多行。 下面顯示了animals.txt示例:
Arachnocampa luminosa,Glow Worm Pongo abelii,Sumatran Orang-utan Felis Lynx,Lynx Spheniscus Humboldti,Humboldt Penguin
animals.txt將包含零行或更多行,每行描述一個動物。 每行包含兩個值,以逗號(,)分隔。 逗號的左側包含動物的科學名稱,逗號的右側包含動物的通用名稱。
您的程序應從animal.txt中讀取這些科學的動物名稱,然后要求用戶輸入多行。 每次,程序都應要求用戶輸入動物的科學名稱。 如果您從animal.txt讀取的數據中存在該科學名稱,則程序應打印出該動物的通用名稱。 否則,如果科學名稱未知,則您的程序應打印出它不知道該動物的信息。 例如:
Scientific name: Spheniscus Humboldti That's the Humboldt Penguin! Scientific name: Callithrix Pygmaea I don't know that animal. Scientific name: Arachnocampa luminosa That's the Glow Worm! Scientific name:
以下是我到目前為止編寫的代碼。 就像您在示例中看到的那樣,如果該動物在列表中,那么它應該打印出該動物的通用名稱(而不是科學名稱)。 當我運行我的代碼時,在示例中,它會正確打印出前兩個代碼,但是當我輸入“ Arachnocampa luminosa”時,它會給出“ That's Humbolt Penguin”。
animals = {}
for i in open('animals.txt'):
sName, cName = i.split(',')
animals[sName] = cName
x = input('Scientific name: ')
while x:
if x in animals:
print("That's the " + cName.rstrip() + "!")
else:
print("I don't know that animal.")
x = input('Scientific name: ')
我在做錯什么導致此錯誤,我該如何解決?
您做錯了,您總是打印從.txt
- cName
讀取的最后一個值。 您應該從字典中獲取有關科學名稱的通用名稱的信息。 范例-
while x:
if x in animals:
print("That's the " + animals[x].rstrip() + "!")
還有一些建議,循環遍歷-
for i in open('animals.txt'):
您應該顯式打開和關閉文件,您可以在此處使用with
語句。 范例-
with open('animals.txt') as f:
for i in f:
sName, cName = i.split(',')
animals[sName] = cName
with
語句將在塊結束時為您處理文件的關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.