用字典中的其他字母替换一个字母

时间:2014-08-26 01:54:52

标签: python-2.7

我想在字典中将字母中的字母替换为字典中的一位数字并添加到列表中:

dictionary = {'a':'oe', 'b':'it'}
string = 'ab'
# return list should be
list = ['ob','eb','ai', 'at']

def replace(string):
       """ 
       Return a list of all possible string
       """
       list = []
       for idx in string:
           if idx is key:
               # do somethin to replace dict[key] with dict[value]
               list.append(string)
               return list

1 个答案:

答案 0 :(得分:0)

如果我理解你想要的东西,应该这样做:

from string import maketrans

dictionary = {'a':'oe', 'b':'it'}
string = 'ab'

def replace(target):
   """ 
   Return a list of all possible string
   """
   result = []
   for k,values in dictionary.iteritems():
     for c in values: 
        trans = maketrans(k, c)
        result.append( target.translate(trans) )

  return result