python - 如何制作一个像lisp的 'mapcar'一样工作的python函数

标签 python functional-programming lisp

我想知道如何制作一个与 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]

最佳答案

使用map,还有一个operator用于添加operator.add:

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

来自documentation . map 将函数作为第一个参数,以及可变数量的iterable 参数。关键是该函数应采用与提供给 map 的可迭代对象一样多的参数。这是唯一要考虑的“限制”。所以,例如:

map(lambda x: x+1,         range(10))
map(lambda x, y: x+y,      range(10), range(10))
map(lambda x, y, z: x+y+z, range(10), range(10), range(10))

等等……

它也可以接受用户定义的任何其他函数:

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

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

关于python - 如何制作一个像lisp的 'mapcar'一样工作的python函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53592586/

相关文章:

python - 如何在 Python 中垂直连接两个数组?

python - 并发.futures 和 Flask-Executor : how to stop all future threads in a thread?

python - 使用python控制线程中的循环

list - 如何获取列表中某个位置项的值?

python - 关闭 Panda3d 应用程序而不关闭整个进程

algorithm - Scala 代码中的性能问题 - O(nlgn) 比 O(n) 快

functional-programming - OCaml 嵌套模式 - 尽管定义了模式但仍存在异常

javascript - 在不使用 Promises 的情况下按顺序执行回调

macros - 添加 f-exprs 是否简化了 LISP 中基本表达式宏的实现?

python - 在 Common Lisp 中管理依赖关系