【发布时间】:2016-02-03 20:57:28
【问题描述】:
我有这个字符串
message = '10100010011'
还有这本词典
codes = {97: '1', 98: '01', 107: '001', 114: '000'}
我需要使用字典将原始消息替换为类似的内容
[97, 98, 114, 97, 107, 97]
我尝试了我自己的方法,这很有效,但是当我使用一些非常大的字符串时,它真的很慢。还有比这更快的方法吗?
codes = dict(zip(codes.values(), codes.keys()))
decoded_mess = []
pom = ""
for i in message:
pom += i
if pom in codes:
decoded_mess.append(codes[pom])
pom = ""
我在Easiest way to replace a string using a dictionary of replacements? 看到了答案,我试过了,但这对我不起作用。可能是因为他们处理的是整个单词,但我有 1 长串 1 和 0。
【问题讨论】:
-
你的字典是不是弄错了?键(或值,目前)不应该都有固定的长度吗?
-
@jonrsharpe 他在解决方案中交换键值。
-
@MarounMaroun 哦...那为什么要单独显示呢?!
-
鉴于当前的限制,您无法更有效地做到这一点。如果你有固定长度的键,那会更容易(因为你可以将字符串切成适当的长度来开始,而不是建立它直到匹配为止)。
-
@jonrsharpe 这些键(1、01、001、000)看起来可能是霍夫曼编码。
标签: python string dictionary substitution