理解示例Spotipy使用内部'for'循环的必要性

2024-09-26 23:23:48 发布

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

我尝试将Spotify API与spotipy库结合使用,但我不了解本文中的代码示例:

https://towardsdatascience.com/making-your-own-discover-weekly-f1ac7546fedb

sourcePlaylist = sp.user_playlist("<source user>", "<Source Playlist ID>")
tracks = sourcePlaylist["tracks"]
songs = tracks["items"] 
while tracks['next']:
    tracks = sp.next(tracks)
    for item in tracks["items"]:
        songs.append(item)

我知道API返回的数据在嵌套字典中。我不明白为什么内部for循环是必要的。你知道吗

如果songs = tracks['items'],那么while循环中的for循环基本上是:

for song in songs:
    songs.append(song)

因为tracks['items']本来就在列表中songs。当songs根据定义等于这个数据时,为什么要把tracks['items']附加到songs?你知道吗


Tags: 数据inapiforsongitemsitemsp
1条回答
网友
1楼 · 发布于 2024-09-26 23:23:48

之所以需要内部for循环,以及为什么重复将tracks["items"]添加到列表songs中是有意义的,是因为Spotify API使用了分页来避免在API响应中返回比所需更多的数据。所以在while循环的每次迭代中tracks都是不同的。你知道吗

它是mentions it in the Spotify API Documentation,但它通常也是跨api发生的事情。例如,如果您有一个API端点返回Spotify上的歌曲列表,那么在单个响应中返回Spotify上的每首歌曲将是不切实际/不可能的。相反,这些数据将被分解成。想要从Spotify检索所有歌曲的人会跟踪他们当前的“页面”,每次都会请求下一个页面,而只想在Spotify上检索歌曲子集的用户可能只会发出一个请求,而完全忽略页面功能。你知道吗

在示例中添加注释:

songs = tracks["items"]  # set songs to be the songs from the initial page of data
while tracks["next"]:  # user-playlist response says there are still pages left
    # tracks["next"] will be an actual URL that will return the next page of results
    tracks = sp.next(tracks) # set tracks to the next page of data after the current one
    # sp.next is a utility method Spotipy provides
    for item in tracks["items"]:  # append each song on the current page to `songs`
        songs.append(item)

也可能有助于了解sp.next的实际作用:

class Spotipy(object):

    ...

    def next(self, result):
        """ returns the next result given a paged result
            Parameters:
                - result - a previously returned paged result
        """
        if result['next']:
            return self._get(result['next'])
        else:
            return None

文章中的例子更加清晰(就像Tomerikoo用extend说的那样):

full_tracks = []
while tracks:
    full_tracks.extend(tracks["items"])
    tracks = sp.next(tracks)  # eventually will be `None` on the final page

相关问题 更多 >

    热门问题