python将列表中的每个项目乘以子列表

时间:2017-04-28 04:32:03

标签: python sublist

我有一个子列表列表,例如:

t = [[1,2,3,4],[2,5,7,9],[7,9,11,4]]

我想将每个子列表乘以一个列表,使每个子列表中的第一项乘以乘数列表中的第一项,每个子列表中的第二项乘以乘数列表中的第二项,乘数列表是:

乘数= [0.1,0.3,0.5,0.8]

因此,最终的结果将是:

结果= [[0.1,0.6,1.5,3.2],[0.2,1.5,3.5,7.2],[0.7,2.7,5.5,3.2]]

我该怎么做?对不起,如果有人质疑这个问题,我一直在寻找几个小时,但没有找到适用的东西。

5 个答案:

答案 0 :(得分:0)

total_result = list()
for v in t:
    result = list()
    for num, mul in zip(v, multiplier):
        result.append(round(num*mul, 2))
    total_result.append(result)

或只是一行

total_result = [[round(num*mul, 2) for num, mul in zip(v, multiplier)] for v in t]

total_result

[[0.1, 0.6, 1.5, 3.2], [0.2, 1.5, 3.5, 7.2], [0.7, 2.7, 5.5, 3.2]]

答案 1 :(得分:0)

numpyNumpy)将处理所有这些:

import numpy as np
t = np.array([ [1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4] ])
multiplier = np.array([0.1, 0.3, 0.5, 0.8])

new_t = [e*multiplier for e in t]

答案 2 :(得分:0)

您可以使用列表理解:

new_list = []
for li in t:
    new_list.append([li[i]*multiplier[i] for i in range(len(multiplier))])

为清楚起见,扩展的迭代版本是:

import * as Router from "koa-router";
import Drawing from "../../models/drawing";

function getRoutesForDrawing(): Router {
    console.log("Inside getRoutes for drawing");
    let route = new Router();
    route.get("/drawing", function(context,next) {
        console.log("Inside /drawing");
        Drawing.find(function(err,drawings) {
            console.log("Not gettig executed");
            context.body = "Welcome";
        });
        //context.body = "Welcome";       
    });
}
export default getRoutesForDrawing();

...

答案 3 :(得分:0)

Numpy可能是最简单的解决方案,但如果您不想这样做:

t = [[1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4]]
multiplier = [0.1, 0.3, 0.5, 0.8]

def mult_lists(operator_list, operand_list):
    # Assuming both lists are same length
    result = []
    for n in range(len(operator_list)):
        result.append(operator_list[n]*operand_list[n])
    return result

multiplied_t = list(map(lambda i: mult_lists(multiplier, i), t)))

mapmult_lists中的每个项目调用t函数,然后将其排列在列表中。

答案 4 :(得分:0)

实际上,numpy让它变得更容易:

import numpy as np
t = np.array([ [1, 2, 3, 4], [2, 5, 7, 9], [7, 9, 11, 4] ])
multiplier = np.array([0.1, 0.3, 0.5, 0.8])
answer = t * multiplier