我在理解字典和for循环时遇到麻烦。 我有一个使用嵌套字典表示歌曲播放列表的示例。在第一个示例中,代码运行正常,但是当我尝试创建函数并尝试清理代码时。它总是说索引超出范围。任何人都可以丢下2美分。
JSON文件中的播放列表示例:
playlist = {
'title': 'faves',
' author': 'Me',
'songs': [
{
'title': 'song1',
'artist': ['john', 'smith'],
'genre': 'Pop',
'duration' : 3.23
},
{
'title': 'song2',
'artist': ['john2'],
'genre': 'Rock',
'duration' : 3.45
},
{
'title': 'song3',
'artist': ['john3', 'smith3'],
'genre': 'Jazz',
'duration' : 2.45
}
]
}
第一个代码字节效果很好,并打印正确的字符串。
sa = f" and {song['artist'][1]}"
for song in playlist['songs']:
print(f"{song['title']} by {song['artist'][0]}{sa if len(song['artist']) >= 2 else ''}, runtime: {song['duration']}, genre: {song['genre']}")
song1 by john and smith3, runtime: 3.23, genre: Pop
song2 by john2, runtime: 3.45, genre: Rock
song3 by john3 and smith3, runtime: 2.45, genre: Jazz
但是在这里,当我尝试运行此命令时,它说索引超出范围。它叫artist_two,但除非一首歌有不止一位艺术家,否则不应该这样做。
def print_playlist(songs):
print(songs)
for song in songs:
title = song['title']
duration = song['duration']
genre = song['genre']
artists = song['artist']
artist_one = song['artist'][0]
artist_two = song['artist'][1]
sa = f" and {artist_two}"
print(f"{title} by {artist_one}{sa if len(artists) >=2 else ''}, runtime: {duration}, genre: {genre}")
print_playlist(playlist['songs'])
答案 0 :(得分:1)
您可以使用此方法在名称之间使用“和”组成字符串。
self.nav[:] = []
这给出了artist_list=["John","Smith"]
y=" and ".join(str(x) for x in artist_list)
print(y)
并且如果您列出艺术家列表:John and Smith
您的输出看起来像["John","Smith","Dave"]
如上面的评论中所述,您假设artist_list中始终至少有2个元素。您应该使用从Concatenate item in list to strings
中发现的类似我的方法答案 1 :(得分:0)
谢谢Zack Tarr
最终代码如下
map