# Sample Code
import datetime
sample = {
"Eat": [
datetime.datetime(2024, 9, 13, 2, 0),
datetime.datetime(2024, 9, 13, 3, 0),
"2024-09-13 20:43:35.440898",
],
"Sleep": [
datetime.datetime(2024, 9, 13, 4, 0),
datetime.datetime(2024, 9, 13, 20, 0),
"2024-09-13 20:43:24.354440",
],
}
# This is the entire function that I am using
def SortObjectives(obj):
temLis = []
temDic = {}
for i in obj:
print(str(obj[i][0].time()))
temLis.append(obj[i][0].time())
temLis.sort()
print(temLis)
temCou = 0
# Recursive Function
def SortObjectivesR(count):
for i in obj:
print(count)
print(str(temLis[count]) + " --From temLis)")
if obj[i][0].time() == temLis[count]:
temDic[i] = obj[i]
print(len(temDic))
print(len(obj))
if len(temDic) == len(obj):
print("Here")
print(temDic)
return temDic
# Why does this return None when it has a literal value???
# Keep in mind that this function only does this when their are two items
# in the obj dictionary when their not in order
# It works when in order and when in the number of items is > or < then 2
else:
count += 1
SortObjectivesR(count)
# return temDic - not part of original code
print(SortObjectivesR(temCou))
# How I find what it returns
# Would put in return statement to save lines, but it returns None
# Under the specific condition mentioned, the alteration of
# Variables work just fine.
return temDic
print(SortObjectives(sample))
我尝试更改项目的顺序和项目数量并进行测试以查看是否会重现问题。我的希望是看看是否有我可以指出的相似之处,但它也是我在代码中指出的具体内容。我根本不明白,这对我来说毫无意义。我还尝试返回简单的值,例如仅返回一个字符串,结果也为 None。
您可以跳过的评论:
为什么当它有文字值时返回 None ???
请记住,此函数仅在它们是两个项目时才执行此操作 在 obj 字典中,当它们不按顺序时 当按顺序且项目数量大于或小于 2 时,它会起作用 应该放入 return 语句来保存行,但它返回 None 在上述特定条件下,变更 变量工作得很好。
这是一个简单的错误,但它有复杂性,使得回顾起来很困难。程序运行时看起来运行正常,乍一看很难看出代码有什么问题,但分析后发现递归没有附加return语句,这意味着递归返回的值丢失了由于上次运行该函数时未给出任何返回值,因此其值为 None。谢谢你,蒂姆·罗伯茨!