所以我有以下列表:
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)]
我想以列表格式获取嵌套列表的各个元素的产品...
所以我要去:
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
请注意,这不是cd和p之间的1对1关系。
我想这样做......
例如,在F#中,我只会执行list.fold,并使用列表作为累加器。是否有python等价物,或者我必须这样做:
function resizeImage(successCallback, errorCallback, file, targetWidth, targetHeight, encodingType) {
...
image.onload = function() {
var imageWidth = targetWidth,
imageHeight = targetHeight;
var canvas = document.createElement('canvas');
var storageFileName;
/* ====== INSERT THIS CODE ==== */
// Maintain aspect ratio (make sure image size is no bigger than target width/height).
if (image.width < image.height) {
var aspectRatio = image.width / image.height;
imageWidth = imageHeight * aspectRatio;
}
else {
var aspectRatio = image.width / image.height;
imageHeight = imageWidth / aspectRatio;
}
/* ====== END OF CODE ADDITION ==== */
canvas.width = imageWidth;
canvas.height = imageHeight;
答案 0 :(得分: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])]
如果您只想要2个小数位。
print [round(i*j,2) for i,j in zip(cd[0],cd[1])]
如果您有多个字符串,请使用
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)]
答案 1 :(得分:3)
你可以这样做:
[reduce(lambda a, b: a*b, x) for x in zip(*cd)]
这适用于多个列表,不需要任何导入。
正如@DSM提到的那样,你还必须“导入functools”并为python3使用“functools.reduce”。
答案 2 :(得分:3)
您可以将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;如果您使用的是过时的Python,则不需要导入reduce
。)
答案 3 :(得分:0)
你有一个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)
答案 4 :(得分:0)
尝试:
out = [ reduce(lambda x, y: x*y, z) for z in zip(*cd) ]