繁体   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