python - 尝试编写一个模拟手机拨号的函数

标签 python python-2.7 python-3.x

我需要编写一个函数,称为 dial_up,它获取一个字符串作为输入并返回一个单词作为输出。

e.g def dial_up('999 666 88'):

预期输出:

'YOU'

就像您在旧手机上调用短信一样,但我不知道如何开始,也许是这样的:

def dial_up(string):
"""
"""


dict = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrt', '8': 'tuv', '9': 'wxyz'}
for key, value in groupby(string):

在此之后我有点卡住了。

Obs:我需要我的函数循环,所以如果我写 ('2222') 它会返回我'a',因为它返回到'a','a' -> 'b' -> 'c' -> 'a'。

最佳答案

num2chars = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrt', '8': 'tuv', '9': 'wxyz'}

def dial_up(string):
    message = ""
    for group in string.split(" "):
        message += num2chars[group[0]][len(group)-1]
    return message

或者:

def dial_up(string):
    return "".join(num2chars[group[0]][len(group)-1] for group in string.split())

关于python - 尝试编写一个模拟手机拨号的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36159244/

相关文章:

python - 如何递归翻译DNA? (没有 while/for 循环,也没有翻译函数)在 Python 中

python - 如何在 django 中使用 HTMLParser 的另一个模块位置

python - 用星号屏蔽 python 中的用户输入

python - n 个数据帧内部连接到最终数据帧

python - 使用 Selenium (Python) 提交 Web 表单后复制结果

python - 如何删除 python 字符串的最后一个 utf8 字符

python-3.x - 如何在 python 中将 dict 列表转换为 json?

python - 如何将片段着色器图像更改保存到图像输出文件?

python - 使用 Python 通过 stderr 和 stdout 处理来自子进程的消息

python - 将 Excel 工作表添加到工作簿末尾