n = [1,[2,[3,[4,5]]],[6,[7,[8,[9]],10]]]
在python中,我想在函数'print_list'中编写一个嵌套函数,该函数以递归方式为每个子列表调用自身。嵌套函数应该有一个额外的参数缩进,用于跟踪每个递归级别的缩进。在实现print_list(n)时,它以下列格式打印嵌套列表'n'
print_list(n)的
.1
..... 2
......... 3
............. 4
............. 5
..... 6
......... 7
............. 8
答案 0 :(得分:0)
我有一种不好的感觉,我正在做你的作业..无论如何..确保你理解代码..
n = [1, [2, [3, [4, 5]]], [6, [7, [8, [9]], 10]]]
def reqprint(inputdata, depth=0):
if isinstance(inputdata, list):
for sublist in inputdata:
reqprint(sublist, depth=depth+1)
else:
print('.' * depth + str(inputdata))
reqprint(n)
运行时
.1
..2
...3
....4
....5
..6
...7
....8
.....9
...10
答案 1 :(得分:0)
import pprint
n = [1, [2, [3, [4, 5]]], [6, [7, [8, [9]], 10]], 11]
def printList(list_name, level = 0):
for sub_element in list_name:
if isinstance(sub_element, list):
printList(sub_element, level+4)
else:
print '.' * level + str(sub_element)
printList(n)
pprint.pprint(n, width=4)
>>> ================================ RESTART ================================
>>>
1
....2
........3
............4
............5
....6
........7
............8
................9
........10
11
[1,
[2,
[3,
[4,
5]]],
[6,
[7,
[8,
[9]],
10]],
11]
>>>