【问题标题】:Force case on dictionary to compare user input in Python强制字典大小写以比较 Python 中的用户输入
【发布时间】:2014-12-11 17:05:41
【问题描述】:

我正在制作一个用户输入决策树,并且我想强制将与输入进行比较的字典转换为小写。我已将 .lower() 放置在不同的位置并不断出错。

not_found = True
while True:
    if OPTIONS == "1" or 'a':
        ARTIST_PICK = str(raw_input(
            "Please pick an artist\n"
            "Or Q to quit: ")).lower
        print ARTIST_PICK

        **entries = allData(filename).data_to_dict()
        for d in entries:
            arts = d['artist']**

        if ARTIST_PICK in arts:
            print "found it"

        elif ARTIST_PICK == 'q':
            break

        else:
            print "Sorry, that artist could not be found. Choose again."
            not_found = False

这是我试图降低并将用户输入与以下内容进行比较的“条目”示例:

[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]

【问题讨论】:

  • 我看到你正在做)).lower。请记住实际调用该方法。请改用)).lower()。另外,if OPTIONS == '1' or 'a' 不会做你认为的那样。
  • 在 lower 之后缺少 () 是我的错字,抱歉。但我的问题是如何将 d['artist'] 设为小写,以便检查用户输入是否是 d['artist'] 中的值?

标签: python python-2.7 dictionary lowercase


【解决方案1】:

如果您的问题只是比较艺术家姓名,那么您可以使用列表推导将所有内容变为小写。

entries = allData(filename).data_to_dict()

if ARTIST_PICK in [ d['artist'].lower() for d in entries ]:
    print("found it")
elif ARTIST_PICK == "q":
    break
else
    print("Sorry, that artist could not be found. Choose again.")

或者,如果您更愿意使用 for 循环(为了便于阅读,稍微重新排列):

if(ARTIST_PICK != 'q'):
    entries = allData(filename).data_to_dict()

    found = False

    for d in entries:
        if ARTIST_PICK == d['artist'].lower():
            found = True
            break
        elif ARTIST_PICK == "q":
            break

    if(found):
        print("found it")
    else:
        print("Sorry, that artist could not be found. Choose again.")
else:
    # handle the case where the input is 'q' here if you want

顺便说一句,原则上您应该像在句子中使用它们一样命名布尔变量。如果未找到变量,则不要将变量 not_found 设置为 False,而是将名为 found 的变量设置为 False 或将 not_found 设置为 True。从长远来看,这会让事情变得更容易。

【讨论】:

  • for 循环不会循环遍历所有 d['artist'] 条目,仅在输入第一项时产生“找到它”。有什么帮助吗?
  • 对。此代码不是for 循环,而是创建所有小写艺术家姓名的列表(带有if 的行)。我将添加一个带有for 循环的示例。
  • 非常感谢您的帮助!
【解决方案2】:

ARTIST_PICK = str(raw_input( "请选择一位艺术家\n" "或Q退出:")).lower()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2018-05-17
    • 2012-06-03
    相关资源
    最近更新 更多