【问题标题】:Python's if key in dictionary not working correctlyPython 的 if 字典中的键无法正常工作
【发布时间】:2017-10-03 11:16:34
【问题描述】:

我正在解决用户输入可以定义变量的编程问题,如下所示:

length = 1

当用户这样做时,我将这对存储在字典中:

{'length': '1'}

问题是,当我稍后尝试检查字典中是否存在某个键时,我总是得到 False,即使它确实存在。这是我的代码:

import math

def main():
    curr_formula = input()
    substitutions = dict()

    while(curr_formula != "0"):
        if("=" in curr_formula):
            split_formula = curr_formula.split("=")
            substitutions[split_formula[0]] = split_formula[1]

        curr_split = curr_formula.split(" ")
        for i in range(len(curr_split)):

            # this if statement never runs for some reason
            if(curr_split[i] in substitutions):
                curr_split[i] = substitutions[curr_split[i]]

        print(''.join(curr_split))

        curr_formula = input()
main()

输入“length = 1”然后“length + 2”应该打印“1 + 2”,但无法检测到密钥已经存在。对此问题的任何见解将不胜感激!

【问题讨论】:

  • while(input != "0"): 在我看来不合适。 input 是一个函数对象,所以它永远不会等于字符串“0”。
  • @Kevin 你是对的,这是一个错字。我在问题中修复了它。谢谢!
  • 注意:python 不需要 ( ) 围绕条件表达式,例如while curr_formula != "0": 是完全合法的规范风格。
  • @AChampion 非常真实!对于各种编程问题类型,经常在不同语言之间切换是一个坏习惯

标签: python python-3.x


【解决方案1】:

当您在'=' 上拆分时,第一个术语之后和第二个之前都有一个空格。

>>> 'length = 1'.split('=')
['length ', ' 1']

而当您在 ' ' 上拆分时,它会被删除。

>>> 'length = 1'.split(' ')
['length', '=', '1']

因此,您的 dict 中的键可能不同。

【讨论】:

  • 啊,解决了。谢谢!一旦超过 SO 的最低接受限制,我将接受您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
  • 2020-09-20
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-24
相关资源
最近更新 更多