这就是我尝试过的:
def recursive_list_counter(l):
sum = 0
for e in l:
if type(e) == type([]):
#print e
sum += 1
recursive_list_counter(e)
return sum
# should be 6 if I count the first also
recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6])
Run Code Online (Sandbox Code Playgroud)
我想使用递归来检索列表中的列表数量,也计算原始列表.
def is_list(p):
return isinstance(p, list)
def deep_reverse(p):
initial = []
for v, e in enumerate(p):
if is_list(e):
#print p[v][::-1]
initial.append(p[v][::-1])
deep_reverse(e)
return initial
p = [1, [2, 3, [4, [5, 6, [7, 8]]]]]
print deep_reverse(p)
Run Code Online (Sandbox Code Playgroud)
我得到了[[[4, [5, 6, [7, 8]]], 3, 2]],至少是预期的(我还没有费心去弄清楚如何不输掉第一个清单[1[...]])[[[[6, 5, [8, 7]], 4], 3, 2]].
正如您所看到的,代码只会反转[ [2, 3]]- > [[3,2]].我做错了什么?我不是吗?
基本上,我如何在列表理解中编写相同的函数?
def blah(n):
if n <= 1:
return 1
return n + blah(n/2)
print blah(32)
Run Code Online (Sandbox Code Playgroud)
除了向自己证明列表理解中任何范围的自定义步骤实际上是可行的之外,我真的不需要这个.