我对编程有点缺乏经验,我对返回函数的工作原理有点困惑。我正在尝试编写一个将函数映射到嵌套列表元素的程序。可变级别表示列表中嵌套级别的次数。我目前可以通过打印我的最终映射列表 totlist 来让程序工作:
def map_nested(listbasket, function, levels): #listbasket is the list that contains lists
totlist=[] #this list will store the list after the function has been mapped to it
for listelement in listbasket:
if levels<=2: #once we get to the level that just contains a list of lists
newlist=list(map(function,listelement))
totlist.append(newlist) #add to final mapped list
else:
map_nested(listelement, function, levels-1) #recursively call for next level
print(totlist)
map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3) # my test function
相反,我想要一些返回 totlist 的东西,但我不知道该怎么做。 每次我尝试返回它时,它只会返回一个空列表或列表的一部分。我觉得我已经尝试了我能想到的所有退货配置。
这将起作用:
import math
def map_nested(listbasket, function, levels): #listbasket is the list that contains lists
totlist=[] #this list will store the list after the function has been mapped to it
for listelement in listbasket:
if levels<=2: #once we get to the level that just contains a list of lists
newlist=list(map(function,listelement))
totlist.append(newlist) #add to final mapped list
else:
totlist.append(map_nested(listelement, function, levels-1))
return totlist
map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3) # my test function
或稍微整洁的解决方案:
import math
def map_nested(input, function):
if type(input) is list:
return [map_nested(e, function) for e in input]
else:
return function(input)
print map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt)
这是递归地将 map_nested
方法应用于层次结构中的每个列表。当递归到达列表中的元素时,它将应用原始调用中提供的函数。
请注意,这适用于任意深度嵌套的列表,也适用于不平衡的嵌套列表(例如,[1, 2, [3, 4]]
)。
我会totlist
一个论点:
def map_nested(listbasket, function, levels, totlist=None):
if totlist is None:
totlist = []
for listelement in listbasket:
if levels <= 2:
newlist = list(map(function, listelement))
totlist.append(newlist) #add to final mapped list
else:
map_nested(listelement, function, levels-1, totlist)
return totlist
现在:
>>> map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt, 3)
[[1.0, 1.4142135623730951],
[1.7320508075688772, 2.0],
[2.23606797749979, 2.449489742783178],
[2.6457513110645907, 2.8284271247461903]]
如果你想简化(而不是手动传递关卡)并随时展平巢,如下所示:
def map_nested_2(lst, f, out=None):
if out is None:
out = []
for item in lst:
if isinstance(item, list):
map_nested_2(item, f, out)
else:
out.append(f(item))
return out
会给:
[1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979,
2.449489742783178, 2.6457513110645907, 2.8284271247461903]