【问题标题】:Dictionaries and Loops in PythonPython中的字典和循环
【发布时间】:2013-11-12 13:45:27
【问题描述】:

编写一个以名为 DB 的字典为中心的程序,其中包含作为键的协议名称和作为值的这些协议的文本描述。没有全局变量。

• 在 ma​​in 中是一个循环,询问用户输入“协议”

• 循环调用 TF 以查看协议(密钥)是否存在于 DB 中。 TF 返回 T 或 F。

• 如果 T 则 main 调用 PT 打印值并继续..

• 如果 F 则 main 调用 ADD 提示输入值并将 KV 对添加到 DB。

循环直到用户输入'end'然后打印数据库

这是我目前所拥有的:

#!/usr/bin/python3

#contains protocol names as keys, and text descriptions of protocols as values
DB= {'ICMP': 'internet control message protocol', 'RIP':'RIP Description',
     'ipv4':'Internet protocol v4', 'ipv6':'IP version 6'}

def TF(x):
    return x in DB

def PT(x):
    print("The protocol you entered is: " , x)
    return x

def ADD(x):
    usr_input = input("Please enter a value to be added to the DB: ")
    description = input("Please enter description for the key: ")
    DB[usr_input] = description


for i in DB:
    user_input = input("Please enter the protocol: ")
    if (user_input == "end"):
        break
    TF(user_input)
    if (TF(user_input) == True):
        PT(user_input)
    else:
        ADD(user_input)

我得到了用户输入的提示,但是每当我在提示符下输入“ICMP”之类的操作时,它只会打印出相同的答案并继续无限循环,直到我按下 Control+D。我在这里做错了什么?即使我输入一个不在字典中的键,它也会做同样的事情。请帮忙。谢谢。

编辑:修复了无限循环问题并编辑了 PT(x) 以显示它正在被调用。现在还修复了问题,以便在 DB 中不存在键值时调用 ADD(x)。

持续存在的问题:即使我输入,例如“ICMP”作为输入,它只返回键本身,而不是与键关联的值?如何让值出现?

其次,现在如果用户输入不存在,则调用 ADD(x),但是,它不会附加到 DB 字典并将其打印出来。相反,我得到以下信息:

Please enter the protocol: ICMP
The protocol you entered is:  ICMP
Please enter the protocol: icmp
Please enter a value to be added to the DB: here here
Please enter description for the key: herererere
Traceback (most recent call last):
  File "D:/Sheridan/Part Time/Linux Architecture w. Network Scripting/Week 8 Code/practise_in_class.py", line 24, in <module>
    for i in DB:
RuntimeError: dictionary changed size during iteration

【问题讨论】:

  • • 在 main 中有一个循环询问用户输入“协议”。 你的“main”块在哪里?您需要在if __name__ == '__main__': 块中编写代码的使用输入部分。而且,您需要运行无限循环,而不是在 DB 上运行循环。

标签: python for-loop dictionary main


【解决方案1】:

首先,您使用的是input,这实际上是在评估用户输入。所以让我用一个例子来告诉你:

>>> input("?")
?>? 1 + 1
2

请改用raw_input。但是,如果您使用的是 Python3,请继续使用 input

您的问题在于TF。您实际上是在检查空字符串是否为空,因此对于任何类型的输入(非空),它将简单地打印出该值,因为 if 语句将评估为 True 甚至如果输入类似于hello world。更好的方法是这样的:

if user_input in DB

这将检查user_input 是否在您的数据库字典的键中。

第三,当您编写此for i in DB: 时,您正在遍历字典中的键对。你为什么首先这样做?如上所述,只需使用in 关键字在字典中搜索键即可。所以,一个正常运行的程序应该是这样的:

DB = {'ICMP': 'internet control message protocol', 'RIP': 'RIP Description',
      'ipv4': 'Internet protocol v4', 'ipv6': 'IP version 6'}


if __name__ == '__main__':
    # Running loop
    while True:
        # Taking user input
        user_input = raw_input("Please enter a protocol, press Q to quit")

        # If the input is Q, then we break the loop
        if user_input == 'Q':
            break

        # If the value of user_input is inside DB, then we print it
        if user_input in DB:
            print DB[user_input]
        # Else, we ask the user to add a description, and add it to our dictionary
        else:
            user_value = raw_input("Please enter a value for your new protocol")
            # Adding to dictionary using the update method
            DB.update({user_input: user_value})

【讨论】:

  • python3中没有raw_input
  • 你没有指定。
  • @user1819786 如果这个回答对你有帮助,请点赞并采纳。
【解决方案2】:

这个TF(user_input) == True 永远是真的。因为DBdictionary 并且它总是!=""。它返回 true 并调用打印输入的PT(user_input)。所以ADD(user_input) 永远不会被调用。

我认为你需要的是:

def TF(x):
    return x in DB

所以如果它存在则返回 true 否则返回 false 以插入它

>>> DB= {'ICMP': 'internet control message protocol', 'RIP':'RIP Description',
...      'ipv4':'Internet protocol v4', 'ipv6':'IP version 6'}
>>> "ICMP" in DB
True
>>> "ICMP-false" in DB
False
>>> 

【讨论】:

  • 那么我该如何做才能调用 ADD(user_input) 并将输入附加到 DB 并打印出来?
  • TF 目前将始终返回 true,如果您将其更改为我在答案中添加的内容,如果它不在数据库中,它将返回 false,因此它将被添加。请注意,您可能不需要像 @Games Brainiac 演示的那样单独的函数
  • 好的,我修好了那个位。请检查我更新的回复。提前致谢!
  • 你也忘了提到他在 DB 上循环,在一个适得其反的 for 循环中。
  • @GamesBrainiac 是的,你是对的。没看到,虽然 true 应该这样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-13
  • 2017-07-21
  • 1970-01-01
  • 2018-02-22
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多