【问题标题】:maketrans alternative for list - python 2.7列表的maketrans替代品-python 2.7
【发布时间】:2018-11-08 19:19:18
【问题描述】:
INPUT = ["a","b","c","d","e","f","g","h","i","j","k"]
OUTPUT = ["20","21","22","23","24","25","26","27","28","29","30"]
TABLE = maketrans(INPUT, OUTPUT)
content = content.translate(TABLE)

TypeError: maketrans() 参数 1 必须是字符串或只读字符缓冲区,而不是列表

我想要的是,例如,如果string =“a”,则返回为“20”。

我无法将 INPUT 和 OUTPUT 转换为字符串,因为它们的大小不同。

最有效的替代方案或调整是什么?

【问题讨论】:

  • 使用像TABLE = str.maketrans(dict(zip(INPUT,OUTPUT))) 这样的字典
  • 不同版本@Dark
  • 那么您应该使用翻译以外的其他工具。您可以制作一个字典,然后使用''.join([d[c] for c in content])
  • 示例,“a”到“20”示例,“b”到“21”示例,“c”到“22”。有一个清晰的模式。我已阅读文档。
  • 所以使用 dict 并不能帮助您获得结果??

标签: python string python-2.7 translate


【解决方案1】:

使用izip_longest(Python 2.x)或zip_longest(Python 3.x):

from itertools import izip_longest

INPUT = ["a","b","c","d","e","f","g","h","i","j","k"]
OUTPUT = ["20","21","22","23","24","25","26","27","28","29","30"]

string = 'a'   # string here

for i, o in izip_longest(INPUT, OUTPUT):
    if i == string:
        print(o)
# 20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2018-08-27
    • 2021-02-11
    • 2014-05-17
    • 2011-04-28
    相关资源
    最近更新 更多