【问题标题】:List append is returning two different lists列表追加返回两个不同的列表
【发布时间】:2014-01-30 23:54:04
【问题描述】:
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 循环中。如何使它们都附加到同一个空列表,而不是两个单独的列表?

【问题讨论】:

  • 尝试 .extend() 而不是 .append() - 但您可能不想在每次循环时都将 playlist 设置为空列表
  • 我试过了,我又试了一次,它返回了这个[u'4', u'k', u'd', u'Y', u'l', u'V', u'x', u'g', u'8', u'P', u'd', u'i', u'V', u'L', u'z', u'X', u'D', u'G', u'Y', u'g', u'e', u'T'] [u'4', u'Q', u'E', u'k', u'W', u'r', u'P', u'h', u's', u'y', u'l', u'z', u'l', u'L', u't', u'T', u'5', u'd', u'r', u'4', u'K', u't']
  • 我怎么能不让播放列表每次都为空?
  • LOL - 不要强制每次都为空;-)
  • 我今天很傻。下面的正确答案让我感到很愚蠢!

标签: python list while-loop append


【解决方案1】:

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

playlist = []

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

playlist = []
while message:

【讨论】:

    【解决方案2】:

    声明列表并打印while loop:

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

    【讨论】:

      猜你喜欢
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2015-03-22
      • 1970-01-01
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多