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

推荐答案

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

Python相关问答推荐

使用Keras的线性回归参数估计

2D空间中的反旋算法

在vscode上使用Python虚拟环境时((env))

海上重叠直方图

计算每个IP的平均值

将JSON对象转换为Dataframe

如何保持服务器发送的事件连接活动?

不能使用Gekko方程'

python sklearn ValueError:使用序列设置数组元素

用SymPy在Python中求解指数函数

从源代码显示不同的输出(机器学习)(Python)

使用Python异步地持久跟踪用户输入

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.

如何在信号的FFT中获得正确的频率幅值

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

来自Airflow Connection的额外参数

分解polars DataFrame列而不重复其他列值

如何关联来自两个Pandas DataFrame列的列表项?

如何在Polars中处理用户自定义函数的多行结果?

更新包含整数范围的列表中的第一个元素