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

标签 python list map-function

我正在尝试在 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 的结果 也是一个可迭代,所以不是列表。

更多 -like 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.

关于python - 如何在 python 中创建自己的 map() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48006242/

相关文章:

javascript - 如何在不递归的情况下将列表转换为二叉树

python - 以奇怪的方式对 Pandas 数据框进行排序和分组

python - map 输出列表破坏了 map 结果

python - 如何从所有满二叉树中采样?

python - 如何使用 QWebEngine 在同一窗口中打开任何链接(_blank)

python 在for循环中删除一个元素

python - 如何判断一个正则表达式是否匹配另一个正则表达式的子集?

python - 如何根据值从列表中选择实例?

scala - 在无形 HList 中映射元组

C++ 转换和 lambda