如何在不使用内置地图或星图的情况下编写类似星图的函数?

这是任务:

创建一个函数my_map_k,该函数采用函数 f 和 k 列出 L 1 ,...,L k,对于任意 k ≥ 1,并返回列表 [f(L 1 [0],...,L k [ 0]),...,F(L 1 [N-1],...,L ķ [N-1])],其中n是最短的长度L列表。

暗示。使用 Python 的*符号来处理任意数量的列表作为参数。

例子:

my_map_k(lambda x, y, z: x*y*z, [3, 2, 5], [2, 7, 9], [1, 2])

应该返回[6, 28]

这是我已经走了多远,但我被卡住了。

def my_map_k(f, *L):
    n = len(min(*L, key=len))
    x=0
    while x < n:        
    return [f(*L[x],) for x in L]
    my_map_k(lambda x, y, z: x*y*z, [3, 2, 5], [2, 7, 9], [1, 2])

问题是,我不能只说有 3 个列表,因为可能还有更多。此外,我看不到如何从所有三个列表中取出第一个元素。


Helenr
浏览 187回答 3
3回答

Cats萌萌

您可以使用依次从每个列表中zip()获取第n个元素,以及一个列表推导式,以使用如此生成的每组参数调用提供的函数:def&nbsp;my_map_k(f,&nbsp;*lists): &nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;[f(*args)&nbsp;for&nbsp;args&nbsp;in&nbsp;zip(*lists)]这是在行动:>>>&nbsp;my_map_k(lambda&nbsp;x,&nbsp;y,&nbsp;z:&nbsp;x*y*z,&nbsp;[3,&nbsp;2,&nbsp;5],&nbsp;[2,&nbsp;7,&nbsp;9],&nbsp;[1,&nbsp;2]) [6,&nbsp;28]

慕姐4208626

我想到了:def my_map_k(f, *L):&nbsp; &nbsp; z = zip(*L)&nbsp; &nbsp; l = list(z)&nbsp; &nbsp; return ([f(*x) for x in l])my_map_k(lambda x, y, z: x*y*z, [3, 2, 5], [2, 7, 9], [1, 2])

月关宝盒

没有辅助函数的解决方案:from operator import adddef my_map_k(f, *L):&nbsp; &nbsp; ind = 0&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield f(*[l[ind] for l in L])&nbsp; &nbsp; &nbsp; &nbsp; except IndexError:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ind += 1result = my_map_k(add, range(5), range(5))print(list(result))# [0, 2, 4, 6, 8]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python