列表或词典的string.makestrans()相当于什么?

时间:2015-10-13 05:19:32

标签: python list translate

使用string.makestrans()时,您可以创建一个逐字符工作的转换表。

例如,此转换表将每个字母移动到两个位置:

import string  

intab = "abcdefghijklmnopqrstuvwxyz"
outtab = "cdefghijklmnopqrstuvwxyzab"
translationtable = string.maketrans(intab, outtab)

如果我有需要翻译的值列表怎么办?

intab = [`TBA', 'RIP', TGIF', 'FAQ']
outtab = ['To Be Announced', 'Rest In Peace', 
                     'Thank God It\'s Friday', 'Frequently Asked Questions']

翻译这样的标准方法是什么?

1 个答案:

答案 0 :(得分:1)

您可以使用zip创建配对,dict创建“翻译”(字典):

intab = ['TBA', 'RIP', 'TGIF', 'FAQ']
outtab = ['To Be Announced', 'Rest In Peace', 
                     'Thank God It\'s Friday', 'Frequently Asked Questions']

translationtable = dict(zip(intab, outtab)) 
# {'TBA': 'To Be Announced', 'TGIF': "Thank God It's Friday", 'FAQ': 'Frequently Asked Questions', 'RIP': 'Rest In Peace'}