gpt4 book ai didi

python - 对带有子列表的可迭代对象的每个元素应用一个函数

转载 作者:行者123 更新时间:2023-12-03 23:33:37 26 4
gpt4 key购买 nike

我正在尝试将函数应用于包含任意子列表子级别的列表的每个元素。像这样。

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,但这不是解决方案,当然,因为列表的内容也可以是字符串、对象...

最佳答案

听起来递归应该可以解决这个问题:

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]]]

关于python - 对带有子列表的可迭代对象的每个元素应用一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65173390/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com