在此函数中,如果列表不为空,我想返回一个列表。要检查列表是否为空,我使用if not data:
并测试它是否充满了我使用elif data:
的东西,但是当return
等于时,不执行len(data)
语句13.可能是什么原因?
当列表为空时,将使用新的start
和end
参数再次调用该函数,直到data
充满某些东西为止。
Class MyClass:
def downloadHistoryOHLC(url, start, end):
http = urllib.request.urlopen(url)
data = json.loads(http.read().decode())
print('length is', len(data)) # Here I test if list is filled
if not data:
''' Add 366 days to start date if list is empty '''
start = datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
start = str(start.isoformat()+'Z')
end = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
end = str(end.isoformat()+'Z')
MyClass.downloadHistoryOHLC(url, start, end) # if list is empty I execute the same function with new parameters
elif data:
return data
执行该函数时,我可以看到列表的长度为13,但没有返回任何数据。
In [844]: mylist = MyClass.downloadHistoryOHLC(start, end, coin_id, name)
length is 0
length is 0
length is 0
length is 0
length is 13
In [845]: mylist
In [846]:
答案 0 :(得分:0)
也许用else代替elif会更好:
else:
return data
答案 1 :(得分:0)
正如Paul在评论部分中所述,调用函数时我错过了返回。
Class MyClass:
def downloadHistoryOHLC(url, start, end):
http = urllib.request.urlopen(url)
data = json.loads(http.read().decode())
print('length is', len(data)) # Here I test if list is filled
if not data:
''' Add 366 days to start date if list is empty '''
start = datetime.strptime(start, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
start = str(start.isoformat()+'Z')
end = datetime.strptime(end, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=366)
end = str(end.isoformat()+'Z')
return(MyClass.downloadHistoryOHLC(url, start, end)) # if list is empty I execute the same function with new parameters
return data