【问题标题】:Applying a dictionary to a string sentence将字典应用于字符串句子
【发布时间】:2018-10-02 04:51:55
【问题描述】:

有没有一种快速的方法可以将给定数量的字母定义的字典应用于包含多个字母的字符串格式的单词?

例如

def decode(code):
key = {"a":1,"b":2,"c":3,"d":4,"e":5}
return key[code]


print decode("eddcab")

从这里回来

544312

我知道它不能简单地工作,但是有一些技巧或简单的方法可以解决这个问题,或者我需要从索引 [1:2] 然后从 [2:3] 分别定义操作直到我到达字符串的末尾?
我正在使用 python 2.7

感谢任何与此相关的提示或建议。

【问题讨论】:

  • 您可以将字符串拆分为字符和for每个字符,您需要在字典中查找,获取值并将其存储在列表中。然后连接该列表的所有元素。

标签: python string python-2.7 dictionary


【解决方案1】:
from string import maketrans

def decode(code):
    key = {"a":1,"b":2,"c":3,"d":4,"e":5}
    keys, values = zip(*key.items())
    return code.translate(maketrans(''.join(keys), ''.join(map(str, values))))

如果dict的值可以是字符串,则不需要map(str, values)


如果values可以是字符串,这可以进一步简化:

def decode(code):
    key = {'a': '1', 'c': '3', 'b': '2', 'e': '5', 'd': '4'}

    return code.translate(
        maketrans(
            *map(''.join, zip(*key.items()))
            )
        )

【讨论】:

    【解决方案2】:

    只需使用列表推导中的字典值重建数字,默认为 0:

    def decode(code):
        key = {"a":1,"b":2,"c":3,"d":4,"e":5}
        return "".join([str(key.get(c,"0")) for c in code])
    
    print(decode("eddcab"))
    

    结果:

    544312
    

    鉴于您根本不需要字典的值,只需使用偏移字符代码:

    def decode(code):
        return "".join([str(ord(c)-ord('a')+1) for c in code])
    

    【讨论】:

    • 你是对的。我被误认为类的常用功能。赞成。
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多