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

Python中基于列表A非零元素位置提取列表B对应元素求和

解决方案

你的代码已经能定位到binary列表中非零元素的位置,接下来只需要把decimal对应位置的元素累加即可,同时满足作业不使用内置函数的要求,具体实现如下:

严格禁用所有内置函数的版本

binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
total = 0
position = 0

# 手动遍历列表,直到索引超出范围
while True:
    try:
        b_element = binary[position]
        if b_element != 0:
            total += decimal[position]
        position += 1
    except IndexError:
        # 访问到不存在的位置时终止循环
        break

print(total)  # 输出结果:48

若允许使用len()的简化版本

如果作业中禁止的只是sum()这类运算内置函数,允许使用len(),可以用更简洁的for循环实现:

binary = [0,1,1,0,0,0]
decimal = [32,16,8,4,2,1]
total = 0

for position in range(len(binary)):
    if binary[position] != 0:
        total += decimal[position]

print(total)  # 输出结果:48

逻辑说明

  1. 初始化total变量存储累加结果,初始值为0
  2. 遍历binary列表的每个位置,判断当前位置元素是否非零
  3. 若元素非零,就把decimal对应位置的元素加到total中
  4. 遍历结束后输出最终的累加结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:35:29