对列表列表中分组的多个列表应用不同的权重 - Python

Applying different weights to multiple lists grouped in list of lists - Python

我有以下列表:

list_of_lists=[[1,2,3], [4,5,2], [3,2,4]]

我想创建一个函数来为每个内部列表应用不同的权重。

所以当我写 weighted_lists(list_of_lists,10,2,5.5):
- 第一个内部列表应该乘以 10
- 第二个内部列表应该乘以 2
- 第三个内部列表应乘以 5.5

所以,结果我应该有以下内容:

weighted_lists=[[10,20,30], [8,10,4], [16.5,11,22]]

请注意,此函数应支持各种数量的内部列表(在某些情况下我们可能有 3 个,在其他情况下我们可能有 400 个)。

给你,lol是列表列表。

def weighted_lists(lol, *weights):
    if len(lol) != len(weights):
        raise IndexError

    return [[weight*x for x in inner] for inner, weight in zip(lol, weights)]

演示:

list_of_lists=[[1,2,3], [4,5,2], [3,2,4]]
print(weighted_lists(list_of_lists, 10, 2, 5.5)) # [[10, 20, 30], [8, 10, 4], [16.5, 11.0, 22.0]]

您可能想查看 numpy 以了解以下内容:

In [14]: import numpy as np

In [15]: list_of_lists=[[1,2,3],[4,5,2],[3,2,4]]

In [16]: weights = [10, 2, 5.5]

In [17]: (np.array(list_of_lists) * np.array(weights)[:, None]).tolist()
Out[17]: [[10.0, 20.0, 30.0], [8.0, 10.0, 4.0], [16.5, 11.0, 22.0]]

如果您更喜欢函数式,可以使用 itertoolsoperator.mul:

list_of_lists = [[1, 2, 3], [4, 5, 2], [3, 2, 4]]
from itertools import izip, starmap, repeat
from operator import mul

def weighted_lists(l, *args):
    return (list(starmap(mul, izip(*(s, repeat(i))))) for s, i in izip(l, args))


print(list(weighted_lists(list_of_lists, 10, 2, 5.5)))
[[10, 20, 30], [8, 10, 4], [16.5, 11.0, 22.0]]

使用enumeratelambda你可以得到同样的结果。

list_of_lists = [[1,2,3], [4,5,2], [3,2,4]]

def weighted_lists(a_list_of_lists, *some_weights):
    weighted_list_of_list = []
    for i, a_list in enumerate(a_list_of_lists):
        new_list = map(lambda value: value * some_weights[i], a_list)
        weighted_list_of_list.append(new_list)

    return weighted_list_of_list

还有一个班轮:

f = lambda x, *y: [map(lambda v: v * y[i], l) for i, l in enumerate(x)]

结果:

>>> f(list_of_lists, 10, 2, 5.5)
[[10, 20, 30], [8, 10, 4], [16.5, 11.0, 22.0]]
>>> weighted_lists(list_of_lists, 10, 2, 5.5)
[[10, 20, 30], [8, 10, 4], [16.5, 11.0, 22.0]]