使用字典或列表组合值

1 投票
1 回答
41 浏览
提问于 2025-04-13 03:08

我正在尝试写一个函数,这个函数可以接受一个列表或字典里的值,然后返回一个大致的组合值。我调整了在这里找到的代码:

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

1 个回答

1

如果我理解正确的话,你可以这样做:

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

撰写回答