应用带有输入列表的函数
Apply a function with lists like inputs
我想从其他列表 (a, b, c) 创建一个新列表 (V) 并使用一个函数,但我想利用 python 并将该函数应用于三个列出而不是逐个元素。
比如我有列表a、b、c;应用函数后的结果应该是V。谢谢。
def mag(a, b, c):
# something sophisticated
return (a+b)*c
a = [1, 5, 7]
b = [4, 8, 3]
c = [2, 6, 3]
V = [10, 78, 30]
只使用内置函数怎么样?喜欢zip
>>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)]
[10, 78, 30]
加上另一个 python 内置函数,map 其中 returns 一个
迭代器,从而使事情变得更快并最终节省内存:
>>> gen = map(lambda uple:mag(*uple), zip(a, b, c))
>>> list(gen)
[10, 78, 30]
您想先压缩参数,然后将函数映射到解压缩的元组上:
from itertools import starmap
starmap(mag, zip(a,b,c))
有关示例,请参阅 here。
您可以使用 map
函数轻松完成此操作:
V = list(map(mag, a, b, c))
另一种解决方案是使用 map
和 lambda
In [16]: list(map(lambda p: mag(*p), zip(a, b, c)))
Out[16]: [10, 78, 30]
我想从其他列表 (a, b, c) 创建一个新列表 (V) 并使用一个函数,但我想利用 python 并将该函数应用于三个列出而不是逐个元素。
比如我有列表a、b、c;应用函数后的结果应该是V。谢谢。
def mag(a, b, c):
# something sophisticated
return (a+b)*c
a = [1, 5, 7]
b = [4, 8, 3]
c = [2, 6, 3]
V = [10, 78, 30]
只使用内置函数怎么样?喜欢zip
>>> [mag(a_, b_, c_) for a_,b_,c_ in zip(a, b, c)]
[10, 78, 30]
加上另一个 python 内置函数,map 其中 returns 一个 迭代器,从而使事情变得更快并最终节省内存:
>>> gen = map(lambda uple:mag(*uple), zip(a, b, c))
>>> list(gen)
[10, 78, 30]
您想先压缩参数,然后将函数映射到解压缩的元组上:
from itertools import starmap
starmap(mag, zip(a,b,c))
有关示例,请参阅 here。
您可以使用 map
函数轻松完成此操作:
V = list(map(mag, a, b, c))
另一种解决方案是使用 map
和 lambda
In [16]: list(map(lambda p: mag(*p), zip(a, b, c)))
Out[16]: [10, 78, 30]