gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:02:44 25 4
gpt4 key购买 nike

我有以下列表:

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

关于python - 对列表列表中分组的多个列表应用不同的权重 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com