如何在 python 中创建自己的 map() 函数

how to create own map() function in python

我正在尝试在 python 中创建内置的 map() 函数。 这里是可以尝试的:

def mapper(func, *sequences):


   if len(sequences) > 1:
       while True:
          list.append(func(sequences[0][0],sequences[0][0],))
       return list

return list

但我真的卡住了,因为如果用户给出例如 100 个参数,我该如何处理这些

调用函数时使用星号*:

def mapper(func, *sequences):
       <b>result = []</b>
       if len(sequences) > 0:
           <b>minl = min(len(subseq) for subseq in sequences)</b>
           <b>for i in range(minl):</b>
              result.append(func(<b>*[subseq[i] for subseq in sequences]</b>))
       return result

这会产生:

>>> import operator
>>> mapper(operator.add, [1,2,4], [3,6,9])
[4, 8, 13]

通过使用星号,我们将可迭代对象解压为函数调用中的单独参数。

请注意,这仍然不完全等价,因为:

  1. sequences应该是iterables,而不是列表本身,所以我们不能总是索引;和
  2. map 的结果也是 可迭代的 ,因此不是列表。

更像 map 函数是:

def mapper(func, *sequences):
    if not sequences:
        raise TypeError('Mapper should have at least two parameters')
    iters = [iter(seq) for seq in sequences]
    while True:
        yield func(*[next(it) for it in iters])

但是请注意,大多数 Python 解释器将实现 map 比 Python 代码更接近解释器,因此使用内置 map 肯定更有效,而不是自己编写。

N.B.: it is better not to use variable names like list, set, dict, etc. since these will override (here locally) the reference to the list type. As a result a call like list(some_iterable) will no longer work.

将序列或序列逻辑的组合部分分开,更容易阅读和理解。

def mapper(func, *args):
    for i in zip(*args):
        yield func(*i)

这里我们使用 Python 内置 zip 如果你想用你自己的实现完全替换它,用下面的 zipper 函数

替换 zip
def zipper(*args):
    for i in range(len(args[0])):
        index_elements = []
        for arg in args:
            index_elements.append(arg[i])
        yield positional_elements