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
逻辑说明
- 初始化
total变量存储累加结果,初始值为0 - 遍历binary列表的每个位置,判断当前位置元素是否非零
- 若元素非零,就把decimal对应位置的元素加到
total中 - 遍历结束后输出最终的累加结果
内容的提问来源于stack exchange,提问作者FirstStep
相关产品推荐
相关产品推荐

