0

这将为我节省大量代码,但我不确定如何实现它。我想将我的变量“totalfactors”设置为 for 循环遍历字典并执行产品操作(Capital Pi Notation)的结果。所以我想我会这样写:

totalfactors = for x in dictionary: dictionary[x]*totalfactors

我知道我可以用几行来写出来,比如:

totalfactors = 1

    for pf in apfactors:
        totalfactors *= (apfactors[pf]+1)

任何帮助都会非常有用!谢谢

4

3 回答 3

4

您可以使用功能内置的reduce. 它将重复(或递归)应用一个函数 - 这里是一个匿名 lambda - 在一个值列表上,建立一些聚合:

>>> reduce(lambda x, y: x * (y + 1), [1, 2, 3])
12

这相当于:

>>> (1 * (2 + 1)) * (3 + 1)
12

如果您需要另一个初始值,可以将其作为最后一个参数传递给 reduce:

>>> 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

可以使用operator模块和生成器表达式更简洁地编写为:

>>> 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
于 2013-06-12T21:30:58.693 回答
2

听起来你可能想考虑做一个 reduce()。例如:

>>> d={'a':1,'b':2,'c':3,'d':4}
>>> reduce(lambda x,y: x*y, d.values())
24
于 2013-06-12T21:31:15.203 回答
0

我试图想办法用发电机做到这一点,但我能想出的只有

import operator
total_product = reduce(operator.mul, dictionary.values(), 1)

我用以下方法对其进行了测试:

factorial = reduce(operator.mul, xrange(1,6), 1)

结果是120。

编辑:

您可能已经知道这一点,但我后来想到了。如果值中有任何非数字数据,只要您至少有一个dictionary.values(),您将得到一个。不过,当您插入字典时,您可能正在处理这个问题。TypeErrorfloat

我搞砸了一点,想出了:

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 并且没有例外。它可能效率较低,但它比未处理的异常更有效。

于 2013-06-12T21:54:52.957 回答