List append返回两个不同的列表

时间:2014-01-12 03:20:16

标签: python list while-loop append

import requests
import json

def decrementList(words):
    for w in [words] + [words[:-x] for x in range(1,len(words))]:
        url = 'http://ws.spotify.com/search/1/track.json?q='
        request = requests.get(url + "%20".join(w))

        json_dict = json.loads(request.content)
        track_title = ' '.join(w)

        for track in json_dict["tracks"]:
            if track["name"].lower() == track_title.lower() and track['href']:
                return "http://open.spotify.com/track/" + track["href"][14:], words[len(w):], track["href"][14:]

    return "Sorry, no more track matches found!", None

if __name__ == "__main__":
    message = "baby asdf".split()
    size = len(message)

    while message:
        href, new_list, for_playlist = decrementList(message)
        message = new_list

        #print href

        playlist = []
        playlist.append(for_playlist)
        print playlist

在上面的代码中,print playlist返回两个单独的列表。我意识到这是因为列表追加发生在while循环中。如何将这些都附加到同一个空列表中,而不是两个单独的列表?

2 个答案:

答案 0 :(得分:2)

这是因为您在调用playlist之前将名称append()重新分配给空列表:

playlist = []

如果你把它放在while循环之前,你应该得到预期的结果。

playlist = []
while message:

答案 1 :(得分:2)

列出声明列表和打印 while loop

playlist = []
while message:
    #....
print playlist