Python,如何在Lambda中展开元组? [英] Python, how to unroll tuples in lambda?

查看:80
本文介绍了Python,如何在Lambda中展开元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个等长列表,我试图用它们得到标量积,但是这种方式行不通:

I have 2 equal-length lists and I am trying to get scalar product of them with, but it does not work this way:

sum(map(lambda a,b: a*b, zip(list1, list2)))

error: TypeError: <lambda>() takes exactly 2 arguments (1 given)

即使这段代码不适合我的任务,在这种情况下是否有任何方法可以强制lambda与元组一起使用?

Even if this code is not good for my task, is there any way to force lambda to work with tuples for such cases?

我想做

lambda x: (a,b)=x;a*b 

但是它不适用于C样式的';' )

But it will not work with C-style ';' )

感谢您的答案,仍然需要学习有关Python的许多知识)

Thank you for answers, still need to learn many things about Python )

推荐答案

好吧,您不需要使用lambda ...

well, you don't need a lambda for this...

sum(a*b for a, b in zip(list1, list2))

甚至zip()也不尽人意...为了避免创建列表,请使用python3或itertools.izip:

even zip() is slightly less than perfect... to avoid creating a list, either use python3, or itertools.izip:

sum(a*b for a, b in itertools.izip(list1, list2))

但是,如果出于某种疯狂的原因,您确实真的想使用lambda,请分别传递每个列表以分别进行映射:

but if, for some craaaaazy reason, you really really wanted to use lambda, pass each list to map seperately:

sum(map(lambda a, b: a*b, list1, list2))

即使这样,您也不需要lambda,operator模块中提供了可调用的产品:

and even then, you didn't need a lambda either, a callable product is available in the operator module:

sum(map(operator.mul, list1, list2))

但是在第一个或第二个示例中使用生成器,通常会更快.

but use the generator in the first or second example, it will usually be faster.

这篇关于Python,如何在Lambda中展开元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆