对于列表或字典, string.makestrans() 的等价物是什么?
What is the equivalent of string.makestrans() for lists or dictionaries?
使用 string.makestrans()
时,您创建了一个逐字翻译 table。
例如,此翻译 table 将每个字母移动到两个位置:
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']
翻译这样的内容的标准方法是什么?
您可以使用 zip
to create the pairs and dict
创建 "translator"(字典):
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'}
使用 string.makestrans()
时,您创建了一个逐字翻译 table。
例如,此翻译 table 将每个字母移动到两个位置:
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']
翻译这样的内容的标准方法是什么?
您可以使用 zip
to create the pairs and dict
创建 "translator"(字典):
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'}