需要在 for 循环中编辑列表.[蟒蛇}.



我正在取一个句子并将其转换为猪拉丁语,但是当我编辑列表中的单词时,它永远不会保留。

sentence = input("Enter a sentence you want to convert to pig latin")
sentence = sentence.split()
for words in sentence:
    if words[0] in "aeiou":
        words = words+'yay'
当我打印句子时,我得到的句子

与我输入的句子相同。

另一种方法(包括一些修复)

sentence = input("Enter a sentence you want to convert to pig latin: ")
sentence = sentence.split()
for i in range(len(sentence)):
    if sentence[i][0] in "aeiou":
        sentence[i] = sentence[i] + 'yay'
sentence = ' '.join(sentence)
print(sentence)

因为你没有改变句子

所以要得到你想要的结果

new_sentence = ''
for word in sentence:
    if word[0] in "aeiou":
        new_sentence += word +'yay' + ' '
    else:
        new_sentence += word + ' '

所以现在打印new_sentence

我将其设置为返回一个字符串,如果您宁愿拥有一个可以轻松完成的列表

new_sentence = []
for word in sentence:
    if word[0] in "aeiou":
        new_sentence.append(word + 'yay')
    else:
        new_sentence.append(word)

如果您正在使用列表,并且想要将列表转换为字符串,那么只需

" ".join(new_sentence)

您似乎并没有更新句子。

sentence = input("Enter a sentence you want to convert to pig latin")
sentence = sentence.split()
# lambda and mapping instead of a loop
sentence = list(map(lambda word: word+'yay' if word[0] in 'aeiou' else word, sentence))
# instead of printing a list, print the sentence
sentence = ' '.join(sentence)
print(sentence)

有点忘记了一些关于Python的for loop的事情,所以我没有使用它。不好意思

最新更新