python - 当累积和超过 0 时,列表中的先进先出配对

标签 python list

我正在尝试实现 FIFO 配对

假设我有一个列表,其中包含 BUY/SHORT 数量和 SELL/COVER 数量,例如:

x = [100.0, -100.0, 100.0, 100.0, -200.0, 200.0, -100.0, -100.0, 100.0,-100.0]

我正在尝试隔离总和等于 0 的买入和卖出。

i.e. x[0] is offset with x[1]
x[2] and x[3] is offset with x[4]

我正在尝试获取列表 x 的索引位置的嵌套列表,如下所示:

[[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]]

如果初始列表是反向的,我希望得到完全相同的结果:

x = [-100.0, 100.0, -100.0, -100.0, 200.0, -200.0, 100.0, 100.0, -100.0,100.0]

差不多,每次累计和超过 0 时,我都会重置配对。

感谢任何帮助!

我已经实现了一个部分解决方案,其中列表具有完美的偏移大小,例如:

def find_matching_position(trade_list):
    solutions = list(zip([i for i, x2 in enumerate(trade_list) if x2 == trade_list[0]],
                         [i for i, x2 in enumerate(trade_list) if x2 == trade_list[0] * -1]))

    return [sorted(x) for x in solutions]

x = [100, 100, -100 , 100, -100, -100]

    find_matching_position(x)
    [[0, 2], [1, 4], [3, 5]]

最佳答案

你可以试试这个:

x = [-100.0, 100.0, -100.0, -100.0, 200.0, -200.0, 100.0, 100.0, -100.0,100.0]
current_sum = 0
current_sub = 0
t1 = []
t2 = []
t3 = []
for i, a in enumerate(x):
   if a >= 0:
      if (current_sum + a)+current_sub == 0:
          t1.append(i)
          t2.append([t1, t3])
          t1 = []
          t3 = []
          current_sum = 0
          current_sub = 0
       else:
          current_sum += a
          t1.append(i)
   else:
       if current_sum + (current_sub + a) == 0:
           t3.append(i)
           t2.append([t1, t3])
           t1 = []
           t3 = []
           current_sum = 0
           current_sub = 0
       else:
           current_sub += a
           t3.append(i)

print(t2)

输出:

[[[0], [1]], [[2, 3], [4]], [[5], [6, 7]], [[8], [9]]]

关于python - 当累积和超过 0 时,列表中的先进先出配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941070/

相关文章:

python - 当分子和分母都很大时如何避免python中的溢出

python - 为什么 IBM 自然语言分类器返回 DecodeError。 Python

javascript - 树 JavaScript 代码不适用于 Internet Explorer

python - max 如何用于混合类型列表

python - 将 "<>" append 到列表中的每个项目

python - psycopg2 AsIs 和 sql 模块之间的区别

python - 使用 pandas 将多个数据框合并在一起

c++ - 代码错误 : (null): 5 duplicate symbols for architecture x86_64

Python-快速选择函数查找中位数

c++ - 来自类的访问列表,在父类中