2013-11-21 35 views
-1

正在使用的元組是如下:通過歌曲的列表迭代時遇到元組

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)) 

專輯的信息是印刷精美,但是當它到達相冊的打印首歌曲是元組的列表曲它要麼打印第一個或最後一個歌曲信息該列表

+1

這是沒有的地方接近正確的** Python **語法。 – HennyH

+0

@HennyH:我看起來沒有什麼明顯的錯誤。也許你不知道[函數註釋](http://www.python.org/dev/peps/pep-3107/)?我沒有使用Python 3,所以我不太清楚如何使用它們,但這些看起來像函數註釋給我。 – user2357112

回答

0

好上,忽略了一個事實,你的方法定義是不正確的蟒蛇,你確切的錯誤是在這裏:

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

+0

定義如何不正確Python? http://www.python.org/dev/peps/pep-3107/ – user2357112