【问题标题】:Python - Creating Dictionaries by reading text files and searching through that dictionaryPython - 通过读取文本文件并搜索该字典来创建字典
【发布时间】:2019-05-05 02:08:58
【问题描述】:

我必须创建一个程序,该程序接受用户的状态输入并返回该状态状态花。我必须阅读的以下文本文件称为“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:

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

【问题讨论】:

标签: python python-3.x dictionary


【解决方案1】:

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

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}')

【讨论】:

    【解决方案2】:

    你的问题是在你的代码中:

    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)
    

    你遍历所有的州/花对,每次都询问州名。因此,如果您有 50 个州/花对,用户将被询问 50 次。这不是你想要的。

    相反,将包含input(...) 语句的行移到循环的外部(即之前)。什么方式,直到 被要求时,循环才会开始。

    至于输入线和循环:

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

    考虑用三个非循环行替换它:

    state = input("Enter state name: ")
    flower = d[state]
    print(flower, "is the State Flower for", state)
    

    就是这样。在循环中无需手动搜索任何内容,因为 dict 对象会搜索您。

    如果您担心用户输入错误的状态名称并且您不希望您的程序抛出异常,您可以将flower = d[state] 行更改为:

    flower = d.get(state, 'Nothing')
    

    d.get(state) 的工作方式与d[state] 几乎相同,只是如果在字典中找不到state,您可以指定将flower 设置为什么(在本例中为"Nothing") .

    【讨论】:

      【解决方案3】:

      您可以使用 Python 3.6+ 简单地做到这一点:

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

      【讨论】:

      • 尝试更清楚地解释为什么这是问题的答案。
      【解决方案4】:

      您可以尝试一个简单的调试。在比较条件之前打印“状态”和“搜索”的值。这种情况没有得到“真”,因此它只是针对用户输入进行迭代:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-01
        • 2013-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多