[英]How do you set a variable equal to the value returned by a function in python
[英]Setting a variable equal to a returned value from a for loop in Python
这样可以节省很多代码,但是我不确定如何实现它。 我想将变量“ totalfactors”设置为for循环遍历字典并执行乘积运算( 大写Pi表示法 )的结果。 所以我想我会这样写:
totalfactors = for x in dictionary: dictionary[x]*totalfactors
我知道我可以这样写成几行:
totalfactors = 1
for pf in apfactors:
totalfactors *= (apfactors[pf]+1)
任何帮助都将非常有用! 谢谢
您可以使用内置的功能 reduce
。 它将在一个值列表上重复(或递归)应用一个函数(这里是一个匿名lambda),建立一些聚合:
>>> reduce(lambda x, y: x * (y + 1), [1, 2, 3])
12
这等效于:
>>> (1 * (2 + 1)) * (3 + 1)
12
如果需要另一个初始值,可以将其作为最后一个参数传递以减少:
>>> reduce(lambda x, y: x * (y + 1), [1, 2, 3], 10)
240
>>> (((10 * (1 + 1)) * (2 + 1)) * (3 + 1))
240
就像@DSM在注释中指出的那样,您可能想要:
>>> reduce(lambda x, y: x * (y + 1), [1, 2, 3], 1) # initializer is 1
>>> from operator import mul
>>> reduce(mul, (v + 1 for v in d.values()))
我猜想,生成器变体更快,但是在2.7上似乎不是(至少对于非常小的字典而言):
In [10]: from operator import mul
In [11]: d = {'a' : 1, 'b' : 2, 'c' : 3}
In [12]: %timeit reduce(lambda x, y: x * (y + 1), d.values(), 1)
1000000 loops, best of 3: 1 us per loop
In [13]: %timeit reduce(mul, (v + 1 for v in d.values()))
1000000 loops, best of 3: 1.23 us per loop
听起来您可能想研究reduce()。 例如:
>>> d={'a':1,'b':2,'c':3,'d':4}
>>> reduce(lambda x,y: x*y, d.values())
24
我试图想办法用发电机来做到这一点,但我所能想到的就是
import operator
total_product = reduce(operator.mul, dictionary.values(), 1)
我用以下方法进行了测试:
factorial = reduce(operator.mul, xrange(1,6), 1)
结果是120。
编辑:
您可能已经知道这一点,但我稍后考虑了。 如果在dictionary.values()
值中有任何非数字数据,则将获得TypeError
,前提是您至少有一个float
。 但是,当您将其插入字典时,您可能正在处理该问题。
我一团糟,想出了:
import numbers
import operator
foo = [1, 2.1, None, 4.5, 7, 'm']
print reduce(operator.mul, [num for num in foo if isinstance(num, numbers.Number)], 1)
这给了我66.15,也没有例外。 它可能效率较低,但比未处理的异常效率更高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.