我试图编写一个函数,它接受列表或字典中的值,并返回近似值的组合.我调整了代码发现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)]