如何使列表推导迭代一个函数

huangapple go评论67阅读模式
英文:

How to make a list comprehension iterate a function

问题

我们想要使用列表推导来迭代一个函数,例如我们想要的是这样的:

list1 = [3, 1, 2]
list2 = [f(f(f())), f(), f(f())]

这是否可能?

英文:

We want a list comprehension to iterate a function, for example this is what we want:

list1 = [3, 1, 2]
list2 = [f(f(f())), f(), f(f())]

How would this be possible?

答案1

得分: 4

写一个函数调用一个函数`n`然后在列表推导中调用它

```python
def call_n(func, n, arg):
    res = arg
    for _ in range(n):
        res = func(res)
    return res

list2 = [call_n(f, i, initial_value) for i in list1]

<details>
<summary>英文:</summary>

Write a function that calls a function `n` times. Then call that in the list comprehension.

def call_n(func, n, arg):
res = arg
for _ in range(n):
res = func(res)
return res

list2 = [call_n(f, i, initial_value) for i in list1]



</details>



huangapple
  • 本文由 发表于 2023年6月19日 06:11:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502719.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定