我有以下代码:
L = [1, x, x**2]
L2 = [1, 2*x]
def my_mul(x,y):
if x == None: return y
if y == None: return x
return x*y
map(my_mul, L, L2)
这产生了我想要的,这是L和L2的元素乘积。
[1, 2*x^2, x^2]
但是,有没有更Python的方法来实现这一目标?
具体而言,是否可以在不定义自己的功能的情况下执行此操作?
下面的代码应该可以满足您的需求
import itertools
import operator
l1 = [1, 2, 3]
l2 = [1, 2, 3, 4]
list(itertools.starmap(operator.mul, itertools.zip_longest(l1, l2, fillvalue=1)))
# result [1, 3, 9, 4]
zip_longest
将压缩并填充较短列表中的缺失值:
itertools.zip_longest(l1, l2, fillvalue=1)
[(1, 1), (2, 2), (3, 3), (1, 4)]
starmap
将乘法运算符应用于每个整数对
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句