簡體   English   中英

如何將循環的每次迭代中的值返回到其中運行的函數?

[英]How do I return the value from each iteration of a loop to the function it is running within?

我正在編寫一個程序,該程序從實時信息服務器中抓取本地總線時間並進行打印。 為了返回所有的公交時間,它這樣做:

while i < len(info["results"]):
    print "Route Number:" + " " + info['results'][i]['route']
    print "Due in" + " " + info["results"][i]["duetime"] + " " + "minutes." + "\n"
    i = i + 1

這樣可以正常工作,並像下面這樣一個接一個地返回所有結果:

航線號:83在12分鍾內交。

航線號:83在25分鍾內交。

路線號碼:83A在39分鍾內到達。

路線號碼:83在55分鍾內交。

但是,當我在另一個腳本中使用此功能時,我將代碼轉換為獲取時間並將其返回到函數中:

def fetchtime(stopnum):
    data = "?stopid={}".format(stopnum)+"&format=json"
    content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
    req = urllib2.urlopen(content + data + "?")

    i = 0 
    info = json.load(req)

    if len(info["results"]) == 0:
        return "Sorry, there's no real time info for this stop!"

    while i < len(info["results"]):
        return "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n"
        i = i + 1 

此方法有效,但是它僅返回服務器給出的列表中的第一條總線,而不是可能有多少條總線。 如何獲得函數的打印結果以返回循環的每次迭代中提供的信息?

您不僅可以列出並返回列表嗎?

businfo = list()
while i < len(info["results"]):
    businfo.append("Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n")
    i = i + 1 

return businfo

您將必須編輯此功能返回的打印命令。

我建議您使用yield語句代替在fetchtime函數中返回。

就像是:

def fetchtime(stopnum):
    data = "?stopid={}".format(stopnum)+"&format=json"
    content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation"
    req = urllib2.urlopen(content + data + "?")

    i = 0 
    info = json.load(req)

    if len(info["results"]) == 0:
        yield "Sorry, there's no real time info for this stop!"

    while i < len(info["results"]):
        yield "Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n"
        i = i + 1 

它將允許您一次選擇一個數據並繼續。

假設info [“ results”]是長度為2的列表,那么您可以這樣做:

>> a = fetchtime(data)
>> next(a)
Route Number: 83 Due in 25 minutes.
>> next(a) 
Route Number: 42 Due in 33 minutes.
>> next(a)
StopIteration Error
or simple do:
>> for each in a:
    print(each)
Route Number: 83 Due in 25 minutes.
Route Number: 42 Due in 33 minutes.
# In case if there would be no results (list would be empty), iterating 
# over "a" would result in:
>> for each in a:
    print(each)
Sorry, there's no real time info for this stop!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM