将字典应用于字符串语句

2024-10-01 00:28:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如

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]的操作,直到我到达字符串的结尾?
我使用的是python2.7

我很感激任何与此相关的提示或建议。你知道吗


Tags: 方法key字符串数量return字典定义def
2条回答
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()))
            )
        )

只需使用列表中的字典值重新生成数字,默认值为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])

相关问题 更多 >