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

如何将两个数组的对应元素相除生成新数组?

实现数组对应元素求商的方法

已知两个数组:
sales = [100, 125, 120]
target = [100, 110, 115]

要生成新数组ach,每个元素为对应位置sales与target的商(保留两位小数后为[1, 1.14, 1.04]),以下是几种实用实现方式:

方法1:Python原生列表推导式

这是最简洁的原生实现,无需额外依赖:

sales = [100, 125, 120]
target = [100, 110, 115]
ach = [round(s / t, 2) for s, t in zip(sales, target)]
print(ach)  # 输出: [1, 1.14, 1.04]
  • zip(sales, target)将两个数组的对应元素一一配对
  • round(s/t, 2)计算商并保留两位小数

方法2:使用NumPy库(适合大规模数据)

如果处理的是大型数组,NumPy的向量运算效率更高:

import numpy as np

sales = np.array([100, 125, 120])
target = np.array([100, 110, 115])
ach = np.round(sales / target, 2).tolist()
print(ach)  # 输出: [1.0, 1.14, 1.04]
  • NumPy数组支持直接逐元素运算,无需手动循环
  • np.round(..., 2)统一处理小数位数,最后转成普通Python列表

方法3:基础循环(适合新手理解逻辑)

如果需要更直观的过程展示,可以用基础循环实现:

sales = [100, 125, 120]
target = [100, 110, 115]
ach = []
for s, t in zip(sales, target):
    ratio = s / t
    ach.append(round(ratio, 2))
print(ach)  # 输出: [1, 1.14, 1.04]

注意事项

如果target数组中存在0元素,会触发除零错误,可提前添加判断处理:

ach = [round(s / t, 2) if t != 0 else 0 for s, t in zip(sales, target)]

(这里将0对应的结果设为0,可根据实际需求调整默认值)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:35:05