我一直得到“只能将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()
使用拉链
你可以用这个
基本上,在这段代码中
sound
是一个列表,animal
在列表上迭代,即动物是列表的单个元素,在第一次迭代中表示cow
,在第二次迭代中表示pig
,在第三次迭代中表示horse
,依此类推但是您将
sound
作为一个完整的列表传递,而不是在verseFor
中传递它的单个元素因此,您必须迭代这两个列表,以逐个元素发送它们的动物和声音元素。如前所述,您可以像这样使用
zip
现在你在声音和动物两个元素上循环。如果您查看
zip
的输出,就会得到以下结果因此,基本上在我提供的代码的第一次迭代中,我们在
ani
中传递cow
,在sou
中传递moo
。然后在下一次迭代中pig
和oink
,依次类推相关问题 更多 >
编程相关推荐