折叠列表以生成lis

2024-04-26 22:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有以下清单:

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]

我想得到嵌套列表中各个元素的乘积。。。在

所以我打算:

^{pr2}$

注意cd和p之间不是1:1的关系。

我只想简单地。。。在

例如,在F#中,我只需要列表.折叠,并使用列表作为累加器。是否有一个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

Tags: in元素列表forlenreturnif关系
3条回答

你可以用列表理解来做。在

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

如果你只想要两个小数位。在

^{pr2}$

如果有多个字符串,请使用

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

您可以将reduce与{}结合使用(我们可以在这里使用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]

(Python3;如果使用过时的Python,则不需要导入reduce。)

您可以这样做:

[reduce(lambda a, b: a*b, x)  for x in zip(*cd)]

这应该适用于多个列表,并且不需要任何导入。在

正如@DSM提到的,您还必须“导入functools”并使用函数工具.reduce“为了Python3。在

相关问题 更多 >