【问题标题】:Letters in String to Dictionary Values字符串中的字母到字典值
【发布时间】:2019-09-09 18:00:31
【问题描述】:

我正在尝试从字符串 'Hello, World!' 中提取字母并使用字典将其转换为值。

我尝试过使用字符串和列表来看看这是否可行,但无法弄清楚。

d ={'H':1, 'e':2, 'l':3, 'o':4,',':5, ' ':6, 'W':7, 'r':8, 'd':9, '!':10}
mystr = 'Hello, World!'
mystr1 = d(mystr)
print(mystr1)

TypeError: 'dict' object is not callable 是我不断收到的错误。

                   'Hello, World!'

我的预期输出是:'12334567483910'

如果可能的话,我还想要一种将数字转换回单词“Hello, World!”的方法

【问题讨论】:

    标签: python-3.x string dictionary


    【解决方案1】:

    您可以通过将字典转换为翻译表然后使用str.translate 方法来做您想做的事情。

    d = {'H':'1', 'e':'2', 'l':'3', 'o':'4',',':'5', ' ':'6', 'W':'7', 'r':'8', 'd':'9', '!':'10'}
    tt = str.maketrans(d)
    print("Hello, World!".translate(tt))
    # 12334567483910
    

    请注意,我们必须将字典的值从整数更改为字符串,否则 str.maketrans 方法会将它们视为 Unicode 序数。

    【讨论】:

      【解决方案2】:

      您需要对 mystr 的每个字符进行迭代。因此,使用get 方法,我们可以从字典中检索值而不会在字符不存在时导致错误(并且将其忽略),for c in mystr 循环遍历每个字符,str 函数转换从字典到字符串的整数(如果字典中的值是字符串,你就不需要它了,尽管你可以使用translate,就像帕特里克的回答一样)。最后,''.join 将所有字符重新组合成一个新字符串。

      代替get 方法,如果您希望它在字符不在字典中时抛出错误,您可以使用d[c] 而不是d.get(c, '')

      d ={'H':1, 'e':2, 'l':3, 'o':4,',':5, ' ':6, 'W':7, 'r':8, 'd':9, '!':10}
      mystr = 'Hello, World'
      encoded_string = ''.join(str(d.get(c, '')) for c in mystr)
      print('Encoded String:', encoded_string)
      
      r = dict((value, key) for key, value in d.items())
      decoded_string = ''.join(r.get(int(c)) for c in encoded_string)
      print('Decoded String:', decoded_string)
      

      结果

      Encoded String: 123345674839
      Decoded String: Hello, World
      

      【讨论】:

      • 我将如何反向操作以将号码恢复为“Hello, World!”?
      • 你可以创建一个反向字典。叫它r,然后叫r = dict((value, key) for key, value in d.items())。然后使用类似的方法来访问它。我已经更新了答案来说明。
      猜你喜欢
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2018-09-11
      • 2011-06-22
      • 2021-11-23
      • 2011-11-11
      • 1970-01-01
      相关资源
      最近更新 更多