编程语言
首页 > 编程语言> > 如何在python中创建自己的map()函数

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

作者:互联网

我正在尝试在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):
       result = []
       if len(sequences) > 0:
           minl = min(len(subseq) for subseq in sequences)
           for i in range(minl):
              result.append(func(*[subseq[i] for subseq in sequences]))
       return result

这将产生:

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

通过使用星号,我们在函数调用中将可迭代项作为单独的参数解压缩.

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

>序列应该是可迭代的,而不是本身的列表,因此我们不能总是索引;和
> 中的映射结果也是可迭代的,因此不是列表.

更像的地图函数将是:

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解释器实现的映射将比Python代码更接近解释器,因此使用内置映射肯定比编写自己的映射更有效.

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.

标签:map-function,list,python,python-3.x,python-3.x
来源: https://codeday.me/bug/20191025/1928833.html