如何从for循环中删除项?

2024-06-25 23:49:54 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着做一个猜谜游戏,你用每个单词的第一个字母猜一首歌的名字,我记下了第一个单词,但下一个单词总是显示一个额外的“u”,有人能帮忙吗

import random
import re
sWord = 0
correct = 0
lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
re.split(r"-", song)
sLists = (song.split("-"))
sList = sLists[0]
sLetter = sLists[0][0]
sWords = sList.split(" ")
sWordAmount = len(sWords)
sOutput = ("")
sGeneration = sList[1:]
for char in sGeneration:
    if char == " ":
        sOutput = sOutput + (" /")
    elif char == "'":
        sOutput = sOutput + (" '")
    elif char == ".":
        sOutput = sOutput + (" .")
    elif char == ",":
        sOutput = sOutput + (" ,")
    elif char == "(":
        sOutput = sOutput + (" (")
    elif char == ")":
        sOutput = sOutput + (" )")
    else:
        for i in range (sWordAmount):
            if char == sWords[i][0]:
                sOutput = sOutput + char
        else:
            sOutput = sOutput + (" _")
print (sLetter + sOutput + " By " + sLists[1])

如果您需要更多信息,请直接询问


Tags: importresongrandom单词splitlineselif
2条回答

您缺少的是else分支中for循环的中断

for i in range(sWordAmount):
    if char == sWords[i][0]:
        sOutput = sOutput + char
        break
else:
    sOutput = sOutput + (" _")

摘自Python Tips

for loops also have an else clause which most of us are unfamiliar with. The else clause executes after the loop completes normally.

因此,一个新词的第一个字母插入了一个额外的_

这可以简化为isalpha()使用下划线代替字母,否则保留标点符号

lines = ["All Star-Smash Mouth", "Don't Stop Believin'-Journey", "Mr. Brightside-The Killers"]
song = random.choice(lines)
name, artist = song.split('-')
s = ''
for word in name.split():
    s += word[0] + ' '.join('_' if l.isalpha() else l for l in word[1:]) + ' /'
print(s[:-1] + ' By ' + artist)

相关问题 更多 >