如何制作一个python函数作为lisp的“mapcar”

2024-04-25 20:22:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何创建一个与lisp的mapcar相同的python函数。在

mapcar lisp documentation

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]

Tags: andofthetoisonfunctionelements
2条回答

这可以通过以下方式实现:sumOfLists = map(sum, zip(list1, list2)) 您也不需要定义sum函数,因为它是内置的。在

使用map,还有一个用于添加operator.add的运算符:

>>> import operator
>>> list(map(operator.add, list1, list2))
[6, 6, 6, 6, 6]

documentation开始。map接受一个函数作为第一个参数,以及一个可变数目的iterable参数。关键是函数应该接受与给定给map的ITerable一样多的参数。这是唯一需要考虑的“限制”。例如:

^{pr2}$

等等。。。在

也可以采用用户定义的任何其他功能:

def checkString(s):
    return isinstance(s, str) and len(s) > 10

>>> list(map(checkString, ["foo", "fooooooooooooooooooooo"]))
[False, True]

相关问题 更多 >