gpt4 book ai didi

Python - 通过读取文本文件并搜索该词典来创建词典

转载 作者:太空狗 更新时间:2023-10-29 22:28:28 25 4
gpt4 key购买 nike

我必须创建一个程序,它接受用户对状态的输入并返回该状态的状态花。我必须阅读的以下文本文件名为“state_flowers.txt”,它包含以下数据

California,Poppy
West Virginia,Rhododendron
South Dakota,Pasque Flower
Connecticut,Mountain Laurel
New York,Rose
Georgia,Cherokee Rose
Washington,Coast Rhododendron
Virgina,American Dogwood
Arizona,Saguaro Cactus
Hawaii,Pua Aloalo
Alabama,Camelia
Illinois,Violet
Indiana,Peony
Delaware,Peach Blossom
Iowa,Wild Prairie Rose
Kansas,Sunflower
Alaska,Forget Me Not
Lousiana,Magnolia
Maine,White Pine Tassel
Massachusetts,Trailing Arbutus
Michigan,Apple Blossom
Minnesota,Lady Slipper
Mississippi,Magnolia
Missouri,Hawthorn
Montana,Bitterroot
Nebraska,Goldenrod
Nevada,Sagebrush
New Hampshire,Lilac
New Jersy,Violet
New Mexico,Yucca Flower
etc......

我在使用我的代码时遇到的问题是,它只会要求输入州名,并一遍又一遍地重复输入而没有任何输出。到目前为止,这是我的代码:

d = {}
myFile = open('state_flowers.txt', 'r')
for line in myFile:
line2=line.split(",")
state = line2[0]
flower = line2[1]
c = len(flower)-1
#Strips the new line symbol
flower = flower[0:c]
d[state] = flower
#matches each state with its flower

for state, flower in d.items():
search = input("Enter state name:") #user enters input of state
if state == search:
print(flower, "is the State Flower for", state)

正如我所说,我的程序要求的只是一遍又一遍的输入。所以它是这样做的:

Enter state name:Maine
Enter state name:Califorina
Enter state name:Texas
Enter state name:
Enter state name:

我觉得我在这方面非常接近,我们将不胜感激任何帮助,并且非常感谢对我做错了什么的清晰解释!谢谢!

最佳答案

你很接近。无需迭代您的字典。 dict 的美妙之处在于它提供了 O(1) access to values给了一把 key 。您只需接受输入并将键输入字典即可:

search = input("Enter state name:")    #user enters input of state
print(d.get(search), "is the State Flower for", search)

使用 Python 3.6+,您可以使用 f-strings 更清楚地编写:

print(f'{d.get(search)} is the State Flower for {search}')

如果状态在您的字典中不存在 d.get(search) 将返回 None。如果您不想在这种情况下打印任何内容,您可以使用 if 语句:

search = input("Enter state name:")    #user enters input of state
if search in d:
print(f'{d[search]} is the State Flower for {search}')

关于Python - 通过读取文本文件并搜索该词典来创建词典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53599555/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com