python - 如何对映射函数执行多个参数,其中一个在python中保持不变? [英] How to do multiple arguments to map function where one remains the same in python?
本文介绍了python - 如何对映射函数执行多个参数,其中一个在python中保持不变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我们有一个函数 add
如下
Let's say we have a function add
as follows
def add(x, y):
return x + y
我们想为数组应用 map 函数
we want to apply map function for an array
map(add, [1, 2, 3], 2)
语义是我想为数组的每个元素添加 2.但是 map
函数在第三个参数中也需要一个列表.
The semantics are I want to add 2 to every element of the array. But the map
function requires a list in the third argument as well.
注意:为了简单起见,我将使用 add
示例.我原来的功能要复杂得多.当然,在 add
函数中设置 y
的默认值是没有问题的,因为每次调用都会改变它.
Note: I am putting the add
example for simplicity. My original function is much more complicated. And of course option of setting the default value of y
in add
function is out of question as it will be changed for every call.
推荐答案
一个选项是列表推导式:
One option is a list comprehension:
[add(x, 2) for x in [1, 2, 3]]
更多选项:
a = [1, 2, 3]
import functools
map(functools.partial(add, y=2), a)
import itertools
map(add, a, itertools.repeat(2, len(a)))
这篇关于python - 如何对映射函数执行多个参数,其中一个在python中保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文