【问题标题】:If key in dictionary returning false when key exists如果键存在时字典中的键返回false
【发布时间】:2015-07-24 19:33:46
【问题描述】:

Python 3.2

这可能真的很愚蠢,但是:

items = {'1': 'ACK', '2': 'RELQ', '3': 'COM'}
choice = input('Choose an option:\n1.ACK\n2.RELQ\n3.COM\n')
print(choice)
if choice in items:
    print(choice)
    option = items[choice]
else:
    print('Input not recognized')

如果你输入 1,它会一直返回

1
Input not recognized

choice in items 返回的是 false?

这应该很容易,但我就是看不到它是什么。

更新:

print(type(choice))` returns str

print(len(choice)) returns 2

print(repr(choice)) returns '1\r'
print(choice[0]) returns 1

输入正在接收带有 input() 的 \r 换行符

【问题讨论】:

  • 这段代码对我有用,运行windows 8 64 bit python 3.4(.1) with IDLE。
  • 好吧,它根本不适合我。我什至使用print(type(choice)) 检查了类型,它返回了str。
  • 检查len(choice)。它可能在某处抓取了一个额外的字符
  • 我的意思是,您使用的运行设置与我的运行设置有何不同。我知道由于 \r 而不是 \n 的使用,字符串比较在 Mac 上会变得不稳定
  • 不错,print(len(choice)) 返回 2 它在哪里抓取了这个额外的字符?

标签: python if-statement semantics


【解决方案1】:

它可能会抓取换行符,因此为了使您的代码正常工作,您应该修剪选择变量。或者,如果您的 dict 键是整数而不是字符串,您可以执行强制转换操作。

编辑: 您的最后一条评论证明了我的观点,因为 [49, 13] 数字 - 13 是回车的 ascii 代码。

只需添加:

choice = choice.strip()

if choice in items:之前

【讨论】:

    【解决方案2】:

    您正在抓取额外的空白字符(\n 或 \r)。获得输入后,只需使用:

    choice = choice.strip()
    

    因此,您的字符串将从两侧修剪。如果起始空白字符很重要,请使用:

    choice = choice.rstrip()
    

    【讨论】:

      【解决方案3】:

      您看到的是bug in Python 3.2.0, fixed in 3.2.1input() 不应给您任何尾随回车/换行符。如果可以的话,我鼓励你升级 Python。

      如果您使用 Python 3.2.0,您必须删除尾随的 \r 字符:

      import os
      choice = input(…).rstrip(os.linesep)  # Robust (no assumption)
      

      或始终使用整数:

      items = {1: …}
      choice = int(input(…))
      

      我想说,就你的情况而言,第二个选择更自然,但如果你还想添加字母作为选择,它就行不通了。

      PS:Łukasz R. 的回答也很好:它提供了修剪空格(尾随空格,...)的额外好处。

      【讨论】:

        【解决方案4】:

        解决此问题的另一种方法是将输入返回值转换为字符串,因为 items 字典中的键是字符串,如下所示:

        items = {'1': 'ACK', '2': 'RELQ', '3': 'COM'}
        choice = input('Choose an option:\n1.ACK\n2.RELQ\n3.COM\n')
        choice = str(choice)
        print(choice)
        if choice in items:
            print(choice)
            option = items[choice]
        else:
            print('Input not recognized')
        

        如果您不关心字典键的类型(无论是字符串、整数...等),您还可以让您的生活更轻松,您可以简单地将它们定义为整数而不是字符串,就像这样:

        items = {1: 'ACK', 2: 'RELQ', 3: 'COM'}
        choice = input('Choose an option:\n1.ACK\n2.RELQ\n3.COM\n')
        print(choice)
        if choice in items:
            print(choice)
            option = items[choice]
        else:
            print('Input not recognized')
        

        这样你就不需要串任何额外的字符并且你节省了额外的编码。

        【讨论】:

          猜你喜欢
          • 2022-08-05
          • 1970-01-01
          • 2016-02-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-05
          • 2021-01-20
          • 2011-09-02
          相关资源
          最近更新 更多