![](/img/trans.png)
[英]python How to convert a dictionary string to the corresponding dictionary?
[英]How to convert corresponding character sequence from a dictionary into a readable string?
我的問題是:
編寫一個名為 decompress 的 function,它接受一個字符串和一個字典作為輸入。 字典將特殊字符串映射到字符序列。 function 遍歷參數字符串,如果字符在字典中,則將其轉換為相應的字符序列。 您的解決方案可能使用迭代,但它必須是遞歸的(它必須調用自身)。 請注意,特殊字符可能是 map 到其中也有特殊字符的字符序列。 例如,在下面的測試一中,符號表將“$”映射到字符串“ y”,而“ ”映射到“c”。 提示:您可以將生成的序列視為另一個字符串,以使用相同的符號表進行解壓縮。
這是我目前擁有的代碼。 我不知道如何從字符序列中獲取值並將它們轉換為可讀的字符串。 我的代碼還引發了位置參數錯誤。
def decompress(a_str, a_dict):
new_string = ""
for char in a_str:
if char in a_dict:
new_string.join(char)
else:
sub_problem = decompress(char, a_dict)
new_string.join(sub_problem)
return new_string
以下是一些 output 示例:
Examples:
>>> d_simple = {'*':'c','#':'00','$':'*y'}
>>> decompress('$3#',d_simple) #Test One
'cy300'
>>> d = {'#':'hem','@':'T#','$':'t#','&':'$ as','*':' do ','%':' to'}
>>> d.update({'^':' someone ', '~':'for ', '+':'~&'})
>>> decompress("@ as can*has%*+ can't. And^has% speak up + has no voices." ,d) #Test Two
"Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."
您的代碼非常接近,我認為您只是想在再次調用a_dict
之前在 a_dict 中查找新/替換字符。
我認為這是一個正確的解決方案?
def decompress(string, table):
new_string = ''
for char in string:
new_char = table.get(char, char)
if new_char == char:
new_string += char
else:
new_string += decompress(new_char, table)
return new_string
d_simple = {'*': 'c', '#': '00', '$': '*y'}
print(decompress('$3#', d_simple)) # Test One
# 'cy300'
d = {'#': 'hem', '@': 'T#', '$': 't#', '&': '$ as', '*': ' do ', '%': ' to'}
d.update({'^': ' someone ', '~': 'for ', '+': '~&'})
print(decompress("@ as can*has%*+ can't. And^has% speak up + has no voices.", d)) # Test Two
# "Them as can do has to do for them as can't. And someone has to speak up for them as has no voices."
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.