[英]fold a list of lists to produce a list
So I've got the following list: 因此,我有以下列表:
cd = [[0.1,0.2,0.1,0.9], [0.2, 0.3, 0.4, 0.1],[0.2,0.3,0.1,0.5]
and I'd like to get the product of the individual elements of the nested lists in a list format... 我想以列表格式获取嵌套列表的各个元素的乘积...
so I'm going for: 所以我要:
p = [(0.1*0.2*0.2),(0.2*0.3*0.3),(0.1*0.4*0.1),(0.9*0.1*0.5)]
note that this isn't a 1 to 1 relationship between cd and p. 请注意,这不是cd和p之间的一对一关系。
I'd like to do it simply... 我只想简单地做...
In F#, for example, I would just do list.fold, and use a list as my accumulator. 例如,在F#中,我只执行list.fold,然后使用列表作为累加器。 Is there a python equivalent, or do I have to do:
是否有等效的python或我必须做:
p = [cd[0]]
if len(cd) > 1:
for i in range(len(cd) - 1):
for j in range(len(p)):
p[j] = p[j]*cd[i+1][j]
return p
You can do it using a list comprehension. 您可以使用列表理解来做到这一点。
cd = [[0.1,0.2,0.1,0.9], [0.2, 0.3, 0.4, 0.1]]
print [i*j for i,j in zip(cd[0],cd[1])]
If you want only 2 decimal places. 如果只想要2个小数位。
print [round(i*j,2) for i,j in zip(cd[0],cd[1])]
If you have multiple strings use 如果您有多个字符串,请使用
cd = [[0.1,0.2,0.1,0.9], [0.2, 0.3, 0.4, 0.1],[1.0,2.0,3.0,4.0]]
from operator import mul
print [reduce(mul, i, 1) for i in zip(*cd)]
You can do this: 你可以这样做:
[reduce(lambda a, b: a*b, x) for x in zip(*cd)]
This should work for multiple lists, and doesn't require any imports. 这应该适用于多个列表,并且不需要任何导入。
As @DSM mentions, you would also have to "import functools" and use "functools.reduce" for python3. 如@DSM所述,您还必须“导入functools”并为python3使用“ functools.reduce”。
You can combine reduce
with zip
(and we could use a lambda here for multiplication, but since we're importing anyway, we might as well use mul
): 您可以将
reduce
与zip
结合使用(我们可以在此处使用lambda进行乘法运算,但是由于无论如何都进行导入,因此我们不妨使用mul
):
>>> from operator import mul
>>> from functools import reduce
>>> cd = [[0.1,0.2,0.1,0.9], [0.2, 0.3, 0.4, 0.1],[0.2,0.3,0.1,0.5]]
>>> [reduce(mul, ops) for ops in zip(*cd)]
[0.004000000000000001, 0.018, 0.004000000000000001, 0.045000000000000005]
(Python 3; you don't need to import reduce
if you're using an outdated Python.) (Python 3;如果您使用的是过时的Python,则无需导入
reduce
。)
You have a general solution with Numpy, working with more than two sublists: 您可以使用Numpy的通用解决方案,使用两个以上的子列表:
import numpy as np
cd = [[0.1,0.2,0.1,0.9], [0.2, 0.3, 0.4, 0.1]]
out = np.apply_along_axis(np.prod, 0, cd)
尝试:
out = [ reduce(lambda x, y: x*y, z) for z in zip(*cd) ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.