我有下面的递归代码,在每个节点上调用SQL查询以获取属于父节点的节点。
这是错误信息:
这是错误信息:
Exception RuntimeError: 'maximum recursion depth exceeded' in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879768c>> ignored
RuntimeError: maximum recursion depth exceeded while calling a Python object
Exception AttributeError: "'DictCursor' object has no attribute 'connection'" in <bound method DictCursor.__del__ of <MySQLdb.cursors.DictCursor object at 0x879776c>> ignored
我调用的获取 SQL 结果的方法:
def returnCategoryQuery(query, variables={}):
cursor = db.cursor(cursors.DictCursor);
catResults = [];
try:
cursor.execute(query, variables);
for categoryRow in cursor.fetchall():
catResults.append(categoryRow['cl_to']);
return catResults;
except Exception, e:
traceback.print_exc();
实际上,我对上述方法没有任何问题,但我还是放在这里以便更好地概述问题。
递归代码:
def leaves(first, path=[]):
if first:
for elem in first:
if elem.lower() != 'someString'.lower():
if elem not in path:
queryVariable = {'title': elem}
for sublist in leaves(returnCategoryQuery(categoryQuery, variables=queryVariable)):
path.append(sublist)
yield sublist
yield elem
调用递归函数
for key, value in idTitleDictionary.iteritems():
for startCategory in value[0]:
print startCategory + " ==== Start Category";
categoryResults = [];
try:
categoryRow = "";
baseCategoryTree[startCategory] = [];
#print categoryQuery % {'title': startCategory};
cursor.execute(categoryQuery, {'title': startCategory});
done = False;
while not done:
categoryRow = cursor.fetchone();
if not categoryRow:
done = True;
continue;
rowValue = categoryRow['cl_to'];
categoryResults.append(rowValue);
except Exception, e:
traceback.print_exc();
try:
print "Printing depth " + str(depth);
baseCategoryTree[startCategory].append(leaves(categoryResults))
except Exception, e:
traceback.print_exc();
打印字典的代码,
print "---Printing-------"
for key, value in baseCategoryTree.iteritems():
print key,
for elem in value[0]:
print elem + ',';
raw_input("Press Enter to continue...")
print
如果递归太深,我应该在调用递归函数时得到错误,但实际上当我打印字典时出现了这个错误。
if first:
检查与for elem in first:
重复。如果查询返回一个空的结果列表,那么对它进行迭代将会仅仅正确地什么都不做,正如你所期望的那样。此外,你可以使用列表推导式更简单地创建该列表(分号是不必要的,通常被认为很丑陋 :))。 - Karl Knechtel