3

我有这个需要转换为小写的 Python 字典。字典包含需要与不区分大小写的输入相对应的数据,例如,它适用于 resp = 'GBR' 或 'gbr'。希望我在这里有意义。任何帮助将不胜感激!

resp = raw_input('Which country is ' + record['name'] + ' in? ')
        print " "
        valid = {'GBR': ['GBR',
                        'United Kingdom',
                        'UK',
                        'Great Britain and Northern Island',
                        'GB'
                        ],
                'IRL': ['IRL',
                        'Eire',
                        'Republic of Ireland'
                        ]
            }
        if resp in valid[record['sov']]:
            answ = 'Yes, ' + record['name'] + ' is in the ' + resp
4

3 回答 3

5

如果它需要对应不区分大小写的输入,我建议.lower()在比较输入和字典值时简单地添加一个调用,而不是为此创建/转换第二个字典。

但是,鉴于您的字典已经是大写的,我会使用.upper()将您的输入转换为大写以匹配您的字典,而不是反过来

于 2012-10-27T17:25:02.487 回答
1

基本上将小写版本的响应与正确答案的小写版本进行比较。

但是你的问题有几件事并不完全清楚:

你到底在存储records什么?在确认“是的,...在...中”时应使用哪个国家/地区名称?您想将用户响应与有效同义词列表进行匹配,对吗?

如果我要写一个城市流行问答游戏,我可能会做这样的事情:

import random

cities = {'Dublin': 'IRL',
          'London': 'GBR',
          }

country_synonyms = {'GBR': ['United Kingdom',
                            'GBR',
                            'UK',
                            'Great Britain and Northern Island',
                            'GB',
                            ],
                    'IRL': ['Republic of Ireland',
                            'IRL',
                            'Eire',
                            ]
                    }

# Pick a random city from our dicts' keys
challenge = random.choice(cities.keys())

# Country code of the correct response, e.g. 'GBR'
correct_cc = cities[challenge]

# Assume the canonical name for a country is first in the list of synonyms
correct_name = country_synonyms[correct_cc][0]

response = raw_input('Which country is %s in? ' % challenge)

# Clean any whitespace
response = response.strip()

lowercase_synonyms = [s.lower() for s in country_synonyms[correct_cc]]

if response.lower() in lowercase_synonyms:
    answer = "Yes, %s is in the %s." % (challenge, correct_name)
else:
    answer = "Sorry, that's wrong. %s is in the %s." % (challenge, correct_name)

print answer

这条线

lowercase_synonyms = [s.lower() for s in country_synonyms[correct_cc]]

使用列表推导将列表中的每个字符串转换country_synonyms[correct_cc]为小写。另一种选择是使用map

import string
# ...
lowercase_synonyms = map(string.lower, country_synonyms[correct_cc])

这会将函数映射string.lower到列表中的每个项目country_synonyms[correct_cc]

于 2012-10-27T18:10:14.057 回答
0

其他答案显示了一种正确的方法,但是如果要将 dict 转换为小写,这是最简单但不是最有效的方法:

>>> import ast
>>> d
{'GBR': ['GBR', 'United Kingdom', 'UK', 'Great Britain and Northern Island', 'GB'], 'IRL': ['IRL', 'Eire', 'Republic of Ireland']}
>>> ast.literal_eval(str(d).lower())
{'gbr': ['gbr', 'united kingdom', 'uk', 'great britain and northern island', 'gb'], 'irl': ['irl', 'eire', 'republic of ireland']}

编辑:eval 中的全局参数。

编辑 2:使用安全的“literal_eval”:

这可用于安全地评估来自不受信任来源的包含 Python 表达式的字符串,而无需自己解析值。

于 2012-10-27T18:16:06.240 回答