我想知道如何创建一个与lisp的mapcar
相同的python函数。在
mapcar operates on successive elements of the lists. function is applied to the first element of each list, then to the second element of each list, and so on. The iteration terminates when the shortest list runs out, and excess elements in other lists are ignored. The value returned by mapcar is a list of the results of successive calls to function.
例如
list1 = [1, 2, 3, 4, 5]
list2 = [5, 4, 3, 2, 1]
def sum(firstNumber, secondNumber):
return firstNumber + secondNumber
sumOfLists = mapcar(sum, list1, list2)
print(sumOfLists)
# [6, 6, 6, 6, 6]
这可以通过以下方式实现:
sumOfLists = map(sum, zip(list1, list2))
您也不需要定义sum
函数,因为它是内置的。在使用
map
,还有一个用于添加operator.add
的运算符:从documentation开始。
^{pr2}$map
接受一个函数作为第一个参数,以及一个可变数目的iterable参数。关键是函数应该接受与给定给map
的ITerable一样多的参数。这是唯一需要考虑的“限制”。例如:等等。。。在
也可以采用用户定义的任何其他功能:
相关问题 更多 >
编程相关推荐