在这个函数中,我想返回一个列表,如果它不是空的。要检查列表是否为空我使用if not data:
并测试它是否填充了我使用elif data:
的东西,但是当return
等于13时len(data)
语句不执行。可能是什么原因?
当列表为空时,使用新的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]:
也许它会更好地使用else而不是elif:
else:
return data
正如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