只能将str(非列表)连接到str

2024-09-27 23:22:32 发布

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

我一直得到“只能将str(而不是list)连接到str”,但我不确定为什么会出现这个错误。我对python还比较陌生,所以如果有任何帮助,我将不胜感激

def oldMacdonald():
    return "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!\n"

def verseFor(animal, sound):
    lyrics = oldMacdonald() + "And on his farm he had a " + animal + ", Ee-igh, Ee-igh, Oh!\n" \
        "With a " + sound + ", " + sound + " here and a " + sound + ", " \
        "" + sound + ".\nHere a " + sound + ", there a " + sound + ", " \
        "everywhere a " + sound + ", " + sound + "\n" + oldMacdonald()

    return lyrics

def main():
    sound = ["moo", "oink", "neigh", "cluck", "bahh"]
    for animal in ["cow", "pig", "horse", "chick", "sheep"]:
        print(verseFor(animal, sound))

main()

Tags: returnmaindefeelistohhadfarm
3条回答

使用拉链

animals = ["cow", "pig", "horse", "chick", "sheep"]
sounds = ["moo", "oink", "neigh", "cluck", "bahh"]
for animal, sound in zip(animals, sounds):
  print(verseFor(animal, sound))

你可以用这个

def oldMacdonald():
    return "Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!\n"

def verseFor(animal, sound):
    lyrics = oldMacdonald() + "And on his farm he had a " + animal + ", Ee-igh, Ee-igh, Oh!\n" \
                                                                        "With a " + sound + ", " + sound + " here and a " + sound + ", " \
                                                                                                                                             "" + sound + ".\nHere a " + sound + ", there a " + sound + ", " \
                                                                                                                                                                                                                 "everywhere a " + sound + ", " + sound + "\n" + oldMacdonald()

    return lyrics

def main():
    for animal,sound in zip(["cow", "pig", "horse", "chick", "sheep"],["moo", "oink", "neigh", "cluck", "bahh"]):
        print(verseFor(animal, sound))

main()

基本上,在这段代码中

sound = ["moo", "oink", "neigh", "cluck", "bahh"]
    for animal in ["cow", "pig", "horse", "chick", "sheep"]:
        print(verseFor(animal, sound))

sound是一个列表,animal在列表上迭代,即动物是列表的单个元素,在第一次迭代中表示cow,在第二次迭代中表示pig,在第三次迭代中表示horse,依此类推

但是您将sound作为一个完整的列表传递,而不是在verseFor中传递它的单个元素

因此,您必须迭代这两个列表,以逐个元素发送它们的动物和声音元素。如前所述,您可以像这样使用zip

sound = ["moo", "oink", "neigh", "cluck", "bahh"]
animal = ["cow", "pig", "horse", "chick", "sheep"]
for ani, sou in zip(animal, sound):
    print(verseFor(ani, sou))

现在你在声音和动物两个元素上循环。如果您查看zip的输出,就会得到以下结果

list(zip(animal,sound))
>>>[('cow', 'moo'),
 ('pig', 'oink'),
 ('horse', 'neigh'),
 ('chick', 'cluck'),
 ('sheep', 'bahh')]

因此,基本上在我提供的代码的第一次迭代中,我们在ani中传递cow,在sou中传递moo。然后在下一次迭代中pigoink,依次类推

相关问题 更多 >

    热门问题