使用字典或列表组合值

问题描述 投票:0回答:1

我正在尝试编写一个函数,该函数获取列表或字典中的值并返回近似值的组合。我调整了here找到的代码:

from itertools import takewhile, combinations, permutations, product

def findPairs(lst, K):
    for i in range(1,len(lst),1):
        print([pair for pair in combinations(lst, i) if sum(pair) >= K-0.01 and sum(pair) <= K+0.01])

使用参数运行此代码时:

K = 1282.66
print(findPairs(lst, K))

我收到以下回复

[(263.09, 883.58, 75.75, 29.88, 30.36), (263.09, 883.58, 75.75, 29.88, 30.37)]

组合正确,并且已找到报告的配对。然而,我想了解更多细节,因为每天我都会以相同的价格购买许多双鞋,因为底座会大得多。我很快就想到是否可以使用列表或字典之类的东西,如下所示:

lst = [['A1',263.09], ['A2',883.58],['A3', 75.75], ['A4',29.88],['A5',30.36],['A6',30.37]['A7',590.72],['A8', 162.45], ['A9',47.25], ['A10',252.98], ['A11',69.57],['A12', 20.24]]

得到以下回复:

[(A1,A2, A3, A4,A5),(263.09, 883.58, 75.75, 29.88, 30.36)], [(A1,A2, A3, A4,A6),(263.09, 883.58, 75.75, 29.88, 30.37)]
python recursion python-itertools
1个回答
0
投票

IIUC,你可以这样做:

from itertools import combinations

def findPairs(lst, K):
    out = [
        comb
        for i in range(1, len(lst))
        for comb in combinations(lst, i)
        if (s := sum(v for _, v in comb)) >= K - 0.01 and s <= K + 0.01
    ]

    return [list(zip(*subl)) for subl in out]

lst = [
    ["A1", 263.09],
    ["A2", 883.58],
    ["A3", 75.75],
    ["A4", 29.88],
    ["A5", 30.36],
    ["A6", 30.37],
    ["A7", 590.72],
    ["A8", 162.45],
    ["A9", 47.25],
    ["A10", 252.98],
    ["A11", 69.57],
    ["A12", 20.24],
]

K = 1282.66
print(findPairs(lst, K))

打印:

[
    [("A1", "A2", "A3", "A4", "A5"), (263.09, 883.58, 75.75, 29.88, 30.36)],
    [("A1", "A2", "A3", "A4", "A6"), (263.09, 883.58, 75.75, 29.88, 30.37)],
]
© www.soinside.com 2019 - 2024. All rights reserved.