英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论