我是计算机编程的新手,我正在尝试编写一个将英语转换为Pig Latin的程序(对于每个单词,将第一个字母移到单词的末尾并添加'ay')。
如果有数字(以数字表示),则将其乘以2并加4。
ex. John has 4 cats --> ndaay ashay 12 atscay)
我得到了第一个猪拉丁部分,但似乎无法找出数字部分。我的代码访问一个文本文件,但这里是执行字符串pig-latin的程序。我在哪里适合数字函数?
def pig_english():
letterlist = [i + i[0] for i in read_script()]
ayList = [i + 'ay' for i in letterlist]
delaylist = [i[1:] for i in ayList]
print (delaylist)
答案 0 :(得分:0)
您可以测试i.isdigit()
是否然后转换为int,但在一次理解中更容易完成所有操作:
def pig_english(words):
ayList = [str(int(i)*2+4) if i.isdigit() else i[1:]+i[0]+"ay" for i in words]
print (ayList)
如果您在多个理解中拆分操作,那么您需要防范整数:
def pig_english(words):
numberlist = [int(i)*2+4 if i.isdigit() else i for i in words]
letterlist = [i if isinstance(i, int) else i + i[0] for i in numberlist]
ayList = [i if isinstance(i, int) else i + 'ay' for i in letterlist]
delaylist = [str(i) if isinstance(i, int) else i[1:] for i in ayList]
print (delaylist)
>>> pig_english("John has 4 cats".split())
['ohnJay', 'ashay', '12', 'atscay']