将消息翻译成摩尔斯电码

时间:2016-05-09 23:56:11

标签: python

我正在尝试将邮件转换为摩尔斯电码。我想知道如何在没有为每一个字母输入替换行(message = message.replace(' a',' .-')的情况下执行此操作。我们的讲师为我们提供了帮助使用这个莫尔斯代码列表。

code = [["a", ".-"],["b","-..."],["c","-.-."],["d","-.."],
 ["e","."],["f","..-."],["g","--."],["h","...."],
 ["i",".."],["j",".---"],["k","-.-"],["l",".-.."],
 ["m","--"],["n","-."],["o","---"],["p",".--."],
 ["q","--.-"],["r",".-."],["s","..."],["t","-"],
 ["u","..-"],["v","...-"],["w",".--"],["x","-..-"],
 ["y","-.--"],["z","--.."]]

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以多次调用str.replace(),而无需每次使用for循环输入for ch, morse in code: line.replace(ch, morse) ,如下所示:

str.replace()

这是一个使用教师列表和import fileinput code = [["a", ".-"],["b","-..."],["c","-.-."],["d","-.."], ["e","."],["f","..-."],["g","--."],["h","...."], ["i",".."],["j",".---"],["k","-.-"],["l",".-.."], ["m","--"],["n","-."],["o","---"],["p",".--."], ["q","--.-"],["r",".-."],["s","..."],["t","-"], ["u","..-"],["v","...-"],["w",".--"],["x","-..-"], ["y","-.--"],["z","--.."]] for line in fileinput.input(): line = line.replace(" ", " ") for ch, morse in code: line = line.replace(ch, morse + " ") print (line) 函数的完整实现。这是非常低效的。希望您的导师能够在未来的课程中向您展示更好的方法。

{{1}}