嵌套运算符
我正在尝试使用 python 2.7、tkinter 中的运算符编写元组列表理解。 Alpha 是原始数据,Beta 是结果。
alpha=[(A,1,1,2),
(B,2,2,2),
(C,3,1,2)]
当我尝试将这些
beta=[(alpha[0],"%.2f"% reduce(mul,alpha[1:])) for alpha in alpha]
beta
[(A,2.00),(B,8.00),(C,6.00)]
但是
beta=[(alpha[0],"%.2f"% reduce(add,alpha[1:])) for alpha in alpha]
beta
[(A,4.00),(B,6.00),(C,6.00)]
组合起来进行嵌套操作时,我被难住了。如何获得
乘积之和?
beta
[(A,16.00),(B,16.00),(C,16.00)]
产品/产品之和?
beta
[(A,0.13),(B,0.44),(C,0.38)]
我尝试了以下各种迭代但没有成功
beta=[(alpha[0],"%.2f"% reduce(add, map(mul,alpha[1:])) for alpha in alpha]
I'm trying to write a tuple list comprehension using operators in python 2.7, tkinter. Alpha is the original data, beta the result.
alpha=[(A,1,1,2),
(B,2,2,2),
(C,3,1,2)]
product
beta=[(alpha[0],"%.2f"% reduce(mul,alpha[1:])) for alpha in alpha]
beta
[(A,2.00),(B,8.00),(C,6.00)]
sum
beta=[(alpha[0],"%.2f"% reduce(add,alpha[1:])) for alpha in alpha]
beta
[(A,4.00),(B,6.00),(C,6.00)]
But when I try to combine these for nested operations, I'm stumped. How do I get the
sum of products?
beta
[(A,16.00),(B,16.00),(C,16.00)]
products / sum of products?
beta
[(A,0.13),(B,0.44),(C,0.38)]
I've tried various iterations of the following with no success
beta=[(alpha[0],"%.2f"% reduce(add, map(mul,alpha[1:])) for alpha in alpha]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法:
我假设
0.44
是一个拼写错误。如果不是,请说明如何计算。Here is one way to do it:
I assume the
0.44
is a typo. If it isn't, please clarify how it should be computed.您可以将匿名函数与reduce一起使用:
you can use anonymous functions with reduce: