2 回答
TA贡献1824条经验 获得超8个赞
您只获得一个键值对的原因是因为每次运行循环时您都在覆盖变量。您可以使用一个简单的列表来累积所有音乐家并在最后打印:
def make_album(artist_name,album_title):
"""Return a dictionary of information about album."""
album_details_1 = {'name': artist_name, 'title': album_title}
return album_details_1
musicians = [] # list of musicians
while True:
print("\nPlease tell me the name of your favorite artist:")
art_name =input("artist name: ")
alb_title=input("album title: ")
musicians.append(make_album(art_name, alb_title)) # add the new musicians to list
repeat = input("Would you like to enter another response? (yes/no) ")
if repeat.lower() == 'no':
break
print(musicians)
输出:
Please tell me the name of your favorite artist:
artist name: 1
album title: 1
Would you like to enter another response? (yes/no) yes
Please tell me the name of your favorite artist:
artist name: 2
album title: 2
Would you like to enter another response? (yes/no) no
[{'name': '1', 'title': '1'}, {'name': '2', 'title': '2'}]
请注意,我曾经repeat.lower()检查输入,这样您的程序将独立于字符串大小写(NO/No/nO/no)而停止。
TA贡献1794条经验 获得超8个赞
问题在于,while 循环要求用户每次迭代都输入艺术家和专辑名称,但它对这些信息没有做任何事情。它只是一遍又一遍地询问用户,直到他们拒绝为止。只有这样才能从最后一个艺术家,专辑对创建一个字典。
当你说你想要多个键值对时,你已经做到了。如果我运行程序并输入艺术家姓名“freddy”和专辑“my_album”,我会得到:
Please tell me the name of your favourite artist:
artist name: freddy
album title: my_album
Would you like to enter another response? (yes/no) no
{'title': 'my_album', 'name': 'freddy'}
请注意,我有一个值为“my_album”的键“title”和一个值为“freddy”的键“name”。所以有2个键值对。
当您说您想要多个键值对时,我假设您的意思是您想要跟踪多个艺术家、专辑名称对。如果是这样,在 Python 中执行此操作的最佳方法是使用元组。你可以有('freddy','my_album')一个元组。使用元组,您不必有任何键。相反,每个项目的位置会告诉您它的含义。在这种情况下,元组的第一项是艺术家姓名,第二项是专辑名称。
然后,使用元组,您可以拥有它们的列表来跟踪所有艺术家、专辑对:
def make_album(artist_name,album_title):
"""Return a tuple of information about album."""
return (artist_name, album_title)
all_tuples = []
while True:
print("\nPlease tell me the name of your favourite artist:")
art_name =input("artist name: ")
alb_title=input("album title: ")
musician = make_album(art_name, alb_title)
all_tuples.append(musician)
repeat = input("Would you like to enter another response? (yes/no) ")
if repeat == 'no':
break
print(all_tuples)
您甚至不需要函数来创建元组: musician = (art_name, alb_title)
或者,更好的是, all_tuples.append((art_name,alb_title))
添加回答
举报