简体   繁体   English

将函数应用于任意嵌套列表的每个项目

[英]Apply a function to every item of an arbitrarily nested list

I have a nested list a = [1, 2, [3, 4], 5] and I want to apply a function that will raise every number to the power of 2. The result will be like this:我有一个嵌套列表a = [1, 2, [3, 4], 5]我想应用一个函数,将每个数字提高到 2 的幂。结果将是这样的:

a = [1, 4, [9, 16], 25]

I tried a = [list(map(lambda x: x * x, x)) for x in a] but it gives this error我尝试a = [list(map(lambda x: x * x, x)) for x in a]但它给出了这个错误

'int' object is not iterable

How we can fix this issue?我们如何解决这个问题? How can I apply a function over a nested list?如何在嵌套列表上应用函数?

You probably need a recursive function that distinguishes between lists and scalars:您可能需要一个区分列表和标量的递归函数:

def square(item):
    if isinstance(item, list):
        return [square(x) for x in item]
    else:
        return item * item

square(a)
#[1, 4, [9, 16], 25]

Incidentally, this approach works for arbitrary-nested lists.顺便说一下,这种方法适用于任意嵌套列表。

Here's a more general solution:这是一个更通用的解决方案:

def apply(item, fun):
    if isinstance(item, list):
        return [apply(x, fun) for x in item]
    else:
        return fun(item)

apply(a, lambda x: x * x)
#[1, 4, [9, 16], 25]

You are decomposing your list into its elements -some of them are lists which can not be multiplied with itself ( [3,4]*[3,4] ).您正在将列表分解为其元素 - 其中一些是不能与自身相乘的列表( [3,4]*[3,4] )。

Not sure if that is smart - but you can use a "recursing" lambda:不确定这是否明智——但您可以使用“递归”lambda:

a =[1, 2, [3, 4], 5]

l = lambda x : x * x if isinstance(x,int) else list(map(l,x))
a = list(map(l, a))

print(a)

Output:输出:

[1, 4, [9, 16], 25]

Works also for "deeper" levels:也适用于“更深层次”的水平:

a =[1, 2, [3, [7,8], 4], 5]

Output:输出:

[1, 4, [9, [49, 64], 16], 25]

but will crash if you mix non-iterables things into the mix但如果你将不可迭代的东西混入其中会崩溃

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM