如何在列表和字典中剥离和使用title()

时间:2017-07-15 19:01:00

标签: python

我知道这是一个新手问题。但是我仍然无法将.strip().title()与列表或字典一起使用。我想将两者标准化,但无法找到。

favorite_languages = {
        'JENNA': 'python',
        'louis': 'C',
        'liOnEl': 'Ruby',
        'maude': 'Javascript',
        }

friends = ['  JeNNa', 'LIONEL  ']


for name in favorite_languages.keys():
    print(name.title().strip())

    if name.title().strip() in friends:
        print("Hi " + name + ", I can see your favorite language is " +
            favorite_languages[name] + "!")

1 个答案:

答案 0 :(得分:1)

首先,规范化favorite_languages

In [605]: fav_lang_norm = { x.strip().title() : favorite_languages[x] for x in favorite_languages }; fav_lang_norm
Out[605]: {'Jenna': 'python', 'Lionel': 'Ruby', 'Louis': 'C', 'Maude': 'Javascript'}

然后,规范化friends列表:

In [606]: friends_norm = [x.strip().title() for x in friends]; friends_norm
Out[606]: ['Jenna', 'Lionel']

迭代规范化词典:

for name, language in fav_lang_norm.items():
    if name in friends_norm:
        print("Hi " + name + ", I can see your favorite language is " +
            language + "!")

你最好希望你的朋友列表不区分大小写...

第二种方法,考虑一下有一百万条记录的巨大favorite_languages字典:

favorite_languages = {...} # 1 million

第1步:仅规范favourite_languages dict

fav_lang_norm = { x.strip().title() : favorite_languages[x] for x in favorite_languages }

第2步:迭代friends列表:

for name in friends: # friends is not normalised
    name_norm = name.strip().title()
    if name_norm in fav_lang_norm:
        print("Hi " + name_norm + ", I can see your favorite language is " +
            fav_lang_norm[name_norm] + "!")