功能说明
构造了一个函数,可以接收一个任意的多维list对象,再接收一个位置list对象,从多维list对象中返回位置list指定的元素。比如get_list_elm(list, [1, 2, 3])
就是返回list[1][2][3]
,这个函数其实是之前写的一个函数(传送门)的逆函数。
问题代码
def get_list_elm(list_0: list, position: list):
list_1 = None
index = None
for num in range(len(position)):
if type(position[num]) != int: # 验证position元素是否全为int
return 'Only int is available!'
if not(position != []): # 验证首次输入的position是否为[]
return '[] is not available!'
else:
index = position[0]
position.pop(0)
if index >= len(list_0): # 验证指定的元素位置是否超过list长度
return 'position wrong!'
else:
list_1 = list_0[index]
if not(position != []): # position元素耗尽,输出元素
return list_1
elif type(list_1) != list: # 当前元素非list类型,无法提取下一维的元素,position指定位置错误
return 'position wrong!'
else:
get_list_elm(list_1, position)
问题分析
print(get_list_elm([[1, 2], 3, 4, 5], [0]))
print(get_list_elm([[1, 2], 3, 4, 5], [0, 0]))
print(get_list_elm([[1, 2], 3, 4, 5], [0, 1]))
print(get_list_elm([[1, 2], 3, 4, 5], [0, 0, 0]))
print(get_list_elm([[1, 2], 3, 4, 5], [1]))
print(get_list_elm([[1, 2], 3, 4, 5], [1, 0]))
print(get_list_elm([[1, 2], 3, 4, 5], [1, None]))
[1, 2]
None
None
None
3
position wrong!
Only int is available!
测试结果显示函数中对格式验证的部分都运行正常,对list
的一维元素的提取也正常。而问题都出在提取高维list
元素的时候,初步推测是和函数递归有关系。
最终确认问题在于最后一个else
的执行语句中,而正常情况下也只有需要进行递归的时候才需要执行这个else
语句,也和问题的情况吻合。
问题主要是这里没有设置return
出口,最里层的递归函数找到指定元素后只会return
给上一层的函数,并不是直接return
给最表层函数。从倒数第二层函数开始就要靠最后一个else
执行语句中的return
层层往上传递。因此从倒数第三层函数开始get_list_elm(list_1, position)
就接收不到值了,因此最表层print
出来的就是None
修改方案
def get_list_elm(list_0: list, position: list):
list_1 = None
index = None
for num in range(len(position)):
if type(position[num]) != int: # 验证position元素是否全为int
return 'Only int is available!'
if not(position != []): # 验证首次输入的position是否为[]
return '[] is not available!'
else:
index = position[0]
position.pop(0)
if index >= len(list_0): # 验证指定的元素位置是否超过list长度
return 'position wrong!'
else:
list_1 = list_0[index]
if not(position != []): # position元素耗尽,输出元素
return list_1
elif type(list_1) != list: # 当前元素非list类型,无法提取下一维的元素,position指定位置错误
return 'position wrong!'
else:
return get_list_elm(list_1, position)