You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的NumPy数组中跳过值并按条件求和收集元素?

NumPy数组累加收集解决方案

给定NumPy数组:

arr = np.array([[1, 300], [2, 100],[3, 0],[4, 0],[5, 50],[6, 100]])

需求是跳过第一个子数组的300,累加后续子数组的第二个值直到总和达到150,并收集对应的子数组。以下是修改后的完整代码:

import numpy as np

arr = np.array([[1, 300], [2, 100],[3, 0],[4, 0],[5, 50],[6, 100]])
total = 0
collected_subarrays = []

# 从索引1开始遍历,跳过第一个子数组
for i in range(1, len(arr)):
    if total >= 150:
        break
    current_value = arr[i][1]
    total += current_value
    # 只收集对累加有贡献的子数组(排除值为0的)
    if current_value != 0:
        collected_subarrays.append(arr[i])

# 可选:将列表转为NumPy数组
collected_arr = np.array(collected_subarrays)
print("收集到的子数组:")
print(collected_arr)
print("累加总和:", total)

关键调整说明:

  • 循环起始索引改为1,直接跳过第一个子数组
  • 新增collected_subarrays列表存储目标子数组,同时过滤掉值为0的子数组(因为它们不影响累加结果,无需收集)
  • 当累加总和达到150时立即终止循环,避免多余计算

运行结果:

收集到的子数组:
[[  2 100]
 [  5  50]]
累加总和: 150

内容的提问来源于stack exchange,提问作者Agustin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 18:55:12