基本上,我正在做一个挑战,我需要从每个单词中取出最后一个字母并将其移到单词的开头,我还需要在每个单词的末尾添加mu,并且我需要在三个单词之后添加emu已显示。我需要帮助的部分是在3个字之后添加emu(在for循环中)。我尝试采用一个变量,每次从列表中获得一个数字时都将其加1,然后检查数字%3 == 0,然后在其后插入'emu'。即使我在插入emu一次后将数字重置为其初始值,但下一次数字%3 == 0时它不会插入正确的位置
这是当前输出:
imu emu odmu tnomu emu wknomu whomu otmu odmu sthimu
我想要的是:
imu odmu tnomu emu wknomu whomu otmu emu odmu sthimu
sentence = 'i do not know how to do this'
sentence = sentence.split()
sentence = " ".join([words[-1:] + words[:-1] + 'mu' for words in sentence])
sentence = sentence.split()
number = 0
for words in sentence:
index = sentence.index(words)
if number % 3 == 0 and number != 0:
number = 0
sentence.insert(index, 'emu')
else:
number += 1
sentence = ' '.join(sentence)
print(sentence)
您可以enumerate
在迭代时用于获取索引。
sentence = 'i do not know how to do this'
sentence = sentence.split()
sentence = " ".join([words[-1:] + words[:-1] + 'mu' for words in sentence])
result = []
for idx, word in enumerate(sentence.split()):
if idx > 1 and idx % 3 == 0:
result.append("emu")
result.append(word)
print(" ".join(result))
您正在做的另一个错误是在迭代时将元素插入数组。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句