0

有这样的问题,这似乎很简单,但由于某种原因在我看来它并没有证明。我有二维列表,我需要在一行中添加一行,以便第一个数字的总和不小于 5(可以只总结下一行)。例如

array([[  0.      ,   3.817549],
       [  3.      ,  21.275711],
       [ 11.      ,  59.286198],
       [ 47.      , 110.136649],
       [132.      , 153.451585],
       [263.      , 171.041259],
       [301.      , 158.872652],
       [198.      , 126.488376],
       [ 50.      , 200.63002 ]])

我需要这样的输出:

array([[  14.      ,   84.3794...],
       [ 47.      , 110.136649],
       [132.      , 153.451585],
       [263.      , 171.041259],
       [301.      , 158.872652],
       [198.      , 126.488376],
       [ 50.      , 200.63002 ]])
4

2 回答 2

0

尝试:

arr = np.array([[  0.      ,   3.817549],
               [  3.      ,  21.275711],
               [ 11.      ,  59.286198],
               [ 47.      , 110.136649],
               [132.      , 153.451585],
               [263.      , 171.041259],
               [301.      , 158.872652],
               [198.      , 126.488376],
               [ 50.      , 200.63002 ]])

for i in range(len(arr)):
    if arr[i, 0] >= 5.0:
        arr = arr[i:, :]
        break
    else:
        arr[i + 1, :] += arr[i, :]
于 2021-04-03T06:59:34.713 回答
0

我不完全确定我是否理解这个问题,但我会尽力提供帮助。

我将通过以下步骤解决此问题:

  1. 创建一个单独的 2D 列表来存储您的最终输出,并创建一个二值累加器列表来临时存储值。将累加器初始化为输入数组的索引 [0][] 处的值

  2. 迭代原始二维列表中的值

  3. 对于每个项目:

    一个。如果 accumulator[0] >= 5,将累加值添加到输出中,然后将累加器设置为 current_index + 1 处的值

    湾。否则,current_index + 1 处的值添加到您的累加器

以下代码能够获取您的输入并重现您想要的确切输出:

# Assuming current_vals is the input list...
  final_vals = []
  accumulator = [current_vals[0][0], current_vals[0][1]]

  for sublist_index in range(1, len(current_vals) - 1):
    if accumulator[0] >= 5:
      final_vals.append([accumulator[0], accumulator[1]])
      accumulator[0] = current_vals[sublist_index][0]
      accumulator[1] = current_vals[sublist_index][1]
    
    else:
      accumulator[0] += current_vals[sublist_index][0]
      accumulator[1] += current_vals[sublist_index][1]

  return final_vals
于 2021-04-03T07:20:36.720 回答