使用else语句返回值

时间:2014-01-10 05:56:43

标签: python function if-statement for-loop return

在我的下面的代码中,最后一个for循环决定是否匹配。如果有匹配,我想返回曲目标题,如果没有匹配,我想返回w

import requests
import json

# initial message
message = "if i can\'t let it go out of my mind"

# split into list
split_message = message.split()

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)
        num_results = json_dict['info']['num_results']

        if num_results > 0:
            num_removed = len(words) - len(w)

            track_title = ' '.join(words)

            #track_title = "If I Can't Take It with Me"

            for value in json_dict["tracks"]:
                if value["name"] == track_title:
                    return track_title
                else:
                    return w

            return num_removed, json_dict, track_title, w


num_words_removed, json_dict, track_title, w = decrementList(split_message)

不幸的是,这不是我理想的解决方案。我真的想重新运行缩短的单词列表,直到有赛道匹配。我试过这个:

for value in json_dict["tracks"]:
    if value["name"] == track_title:
        return track_title
    else:
        decrementList(w)

但是,我得到了某种无限循环并超时了我的请求。这在我的脑海里是有道理的。如果没有跟踪匹配,请选择存储在“w”中的缩短列表,然后通过decrementList函数重新运行。

所以,我想我有两个问题。如何在else语句中返回两个值,如何在找到跟踪匹配之前重新运行缩短的列表。

1 个答案:

答案 0 :(得分:1)

首先,您需要考虑要返回的内容。似乎你没有决定那个,因为有时你会返回一个值(track_titlew),有时你会返回一个元组(num_removed, json_dict, track_title, w)。这个我不能为你做,这取决于你以后需要什么。

除此之外,我认为你应该使用一个生成器来产生结果,直到调用者满意为止(首先是最好的,然后降低匹配质量,即匹配单词越来越少)。看看我的代码版本:

import requests
import json

# initial message
message = "if i can't let it go out of my mind"

# split into list
split_message = message.split()

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)
        num_results = json_dict['info']['num_results']

        if num_results > 0:
            num_removed = len(words) - len(w)

            track_title = ' '.join(w)

            for track in json_dict["tracks"]:
                if track["name"].lower().startswith(track_title.lower()):
                    yield num_removed, track, track["name"], w

def quote(s):
   return '"' + ('%r' % ("'"+s.encode('utf-8')))[2:]

for num_words_removed, track, track_name, w in decrementList(split_message):
   print '%2d %s by %s (track %d on %s from %s)' % (
     num_words_removed,
     quote(track_name),
     quote(track['artists'][0]['name']),
     int(track['track-number']),
     quote(track['album']['name']),
     track['album']['released'])