在遍历歌曲元组列表时遇到问题

2024-04-26 18:07:19 发布

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

使用的元组如下:

Album = namedtuple('Album', 'id artist title year songs')

# id is a unique ID number; artist and title are strings; year is a number,
#   the year the song was released; songs is a list of Songs

Song = namedtuple('Song', 'track title length play_count')

# track is the track number; title is a string; length is the number of
#   seconds long the song is; play_count is the number of times the user
#   has listened to the song

def Song_str(S: Song)->str:
    '''Takes a song and returns a string containing that songs
    information in an easily readible format'''

    return '{:12}{}\n{:12}{}\n{:12}{}\n{:12}{}'.format('Track:', S.track,
                                                       'Title:', S.title,
                                                       'Length:', S.length,
                                                       'Play Count:', S.play_count)

def Album_str(a: Album)->str:
    '''Takes an album and returns a string containing that songs
    information in an easily readible format'''

    Album_Songs = a.songs
    for i in range(0, len(Album_Songs)):
            String = Song_str(Album_Songs[i])+ '\n'

    return '{:10}{}\n{:10}{}\n{:10}{}\n{:10}{}\n\n{}\n{}'.format('ID:', a.id,
                                                                'Artist:', a.artist,
                                                                'Title:', a.title,
                                                                'Year:', a.year,
                                                                'List of Songs:', String)

print(Album_str(AN ALBUM))

专辑信息打印很好,但当打印专辑的歌曲时,这是一个元组歌曲列表,它将打印列表中的第一首或最后一首歌曲信息


Tags: oftheidformatnumberalbumsongtitle
1条回答
网友
1楼 · 发布于 2024-04-26 18:07:19

好吧,忽略您的方法定义不是正确的python这一事实,您的确切错误在这里:

String = Song_str(Album_Songs[i])+ '\n'

每一次专辑的迭代,您都要建立一个名为String的变量。以下是你真正想要的:

def Album_str(a):
    '''Takes an album and returns a string containing that songs
    information in an easily readible format'''

    Album_Songs = a.songs
    list_of_songs = []
    for album_song in Album_Songs:  # Don't use list indexing, just iterate over it.
        list_of_songs.append(Song_str(album_song))

    return '{:10}{}\n{:10}{}\n{:10}{}\n{:10}{}\n\n{}\n{}'.format('ID:', a.id,
                                                                'Artist:', a.artist,
                                                                'Title:', a.title,
                                                                'Year:', a.year,
                                                                'List of Songs:', '\n'.join(list_of_songs))

另外,不要使用变量名String。你知道吗

相关问题 更多 >