以新名称改变旧名字的pythonic方式

时间:2014-11-14 13:20:55

标签: python

我必须将oldnames替换为程序中的newnames,如下所示:

oldnames = ['apple','banana','sheep']

for oldname in oldnames:
    if oldname == 'apple':
        newname = 'monkey'

    if oldname == 'banana':
        newname = 'monkey'

    if oldname == 'sheep':
        newname = 'lion'

我的程序运行良好,但想知道最好的pythonic方式是什么?

3 个答案:

答案 0 :(得分:6)

您可以使用字典来处理替换,例如

>>> replacements = {'apple':'monkey',
                    'banana':'monkey',
                    'sheep':'lion'}
>>> s = "The apple and the banana saw a sheep"
>>> ' '.join(replacements.get(word,word) for word in s.split())
'The monkey and the monkey saw a lion'

答案 1 :(得分:1)

还使用字典,但我认为这更简单:

# Original values
oldnames = ["apple", "banana", "sheep"]

# Conversion table
translate = {
    "apple": "monkey",
    "banana": "monkey",
    "sheep": "lion",
}

# For each oldname, get the translated value
newnames = [translate.get(x) for x in oldnames]

答案 2 :(得分:0)

更加pythonic

oldnames = ["apple", "banana", "sheep"]
translate = { "apple": "monkey", "banana": "monkey", "sheep": "lion" }

newnames = map(translate.get, oldnames)