gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:32:46 24 4
gpt4 key购买 nike

这是任务:

Make a function my_map_k that as arguments takes a function f and k lists L1,...,Lk, for an arbitrary k ≥ 1, and returns the list [f(L1[0],...,Lk[0]),...,f(L1[n-1],...,Lk[n-1])], where n is the length of the shortest Li list.

Hint. Use Python's * notation to handle an arbitrary number of lists as arguments.

Example:

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

should return [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 个列表,因为可能还有更多。此外,我看不出如何从所有三个列表中取出第一个元素。

最佳答案

您可以使用 zip()依次从每个列表中取出第 n 个元素,然后 list comprehension使用生成的每组参数调用提供的函数:

def my_map_k(f, *lists):
return [f(*args) for args in zip(*lists)]

这是实际操作:

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

关于python - 如何在不使用内置 map 或星图的情况下编写类似星图的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55063613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com