如何使用itertools获得每个参数的元组而不是最终结果?

2024-05-05 20:44:03 发布

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

我尝试将三个列表的元素相互结合起来。我想以一种特定的方式将每个元素与每个元素结合起来:

元素*元素**元素

我想要价值观​​每个参数的。条件是不超过某个总值

实际上我用的是itertools和product。我能够接收最高的总值,但不能接收每个参数的值。我不知道´我不知道如何整合这个条件

from itertools import product

List1 = list(range(1,4))
List2 = list(range(4,8))
List3 = list(range(3,7))

result = ([m*(n**o) for m,n,o in product(List1,List2,List3)])
max(result)

输出实际上是352947,但我希望类似于[4,8,7]。在下一步中,我想添加一个条件。我要每个参数的值,但总数不能超过15000。你们能帮我吗


Tags: 元素列表参数方式rangeresultproduct条件
1条回答
网友
1楼 · 发布于 2024-05-05 20:44:03

在元组中包含mno以及计算值m*(n**o),作为列表中的每个元素。然后使用lambda获取结果列表的最大值,使用计算值作为键:

from itertools import product

List1 = list(range(1,4))
List2 = list(range(4,8))
List3 = list(range(3,7))

result = ([(m, n, o, m*(n**o)) for m,n,o in product(List1,List2,List3)])
max_m, max_n, max_o, max_value = max(result, key=lambda tup: tup[3])

相关问题 更多 >