在具有子列表的iterable的每个元素上应用函数

2024-06-16 10:45:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图对包含任意子列表子级别的列表的每个元素应用一个函数。像这样

a = [1,2,3]
b = [[1,2,3],[4,5,6]]
c = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]

function = lambda x: x+1
def apply(iterable,f): 
    # do stuff here
print(apply(a,function)) # [2,3,4]
print(apply(b,function)) # [[2,3,4],[5,6,7]]
print(apply(c,function)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]

基本上,我找不到编写apply函数的方法。我尝试使用numpy,但这当然不是解决方案,因为列表的内容也可以是字符串、对象


Tags: 方法lambda函数元素列表heredeffunction
3条回答

如果所有嵌套列表的形状相同,则可以使用numpy执行此操作:

import numpy as np

ary = np.array([['a', 'b'], ['c', 'd'], ['e', 'f']])
res = np.vectorize(lambda c: c + ':)')(ary)
print(res)
# [['a:)' 'b:)']
#  ['c:)' 'd:)']
#  ['e:)' 'f:)']]

这里有一种方法。请注意,字符串也是可编辑的,因此根据您的用例,您可能需要添加更多检查

def apply(iterable, f):
    try:
        iterator = iter(iterable)
        for i in iterator:
            apply(i, f)
    except Exception as e:
        f(iterable)

c = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]
apply(c, print)

听起来递归应该能够解决这个问题:

a = [1,2,3]
b = [[1,2,3], [4,5,6]]
c = [[[1,2,3], [4,5,6]], [[7,8,9], [10,11,12]]]


f = lambda x : x+1

def apply(iterable, f): 
    # suggestion by Jérôme:
    # from collections.abc import Iterable and use
    # isinstance(iterable, collections.abc.Iterable) so it works for tuples etc. 
    if isinstance(iterable, list):
        # apply function to each element
        return [apply(w, f) for w in iterable]
    else:
        return f(iterable)

print(apply(a, f)) # [2,3,4]
print(apply(b, f)) # [[2,3,4],[5,6,7]]
print(apply(c, f)) # [[[2,3,4],[5,6,7]],[[8,9,10],[11,12,13]]]

相关问题 更多 >