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

Python按索引检测两个列表差异并输出差异位置的实现方案

原代码问题排查

你写的代码没有输出,核心问题是l1.index(i)的用法不符合需求:list.index(元素)只会返回该元素在列表中第一次出现的索引,遍历l1时前4个元素都是0,l1.index(i)永远返回0,永远不会检测到索引3(从1计数为第4位)的差异,因此没有输出。

正确实现方案

基础版(适配两列表长度相同的场景)

直接用enumerate同时遍历索引和对应值,逐位对比即可:

l1=[0,0,0,0,1,1,1,1]
l2=[0,0,0,1,1,1,1,1]

for idx, value in enumerate(l1):
    if value != l2[idx]:
        # 按你需要从1计数的需求,索引+1后输出,即可得到预期结果4
        print(idx + 1)

运行上述代码,输出结果为4,符合你的预期。

进阶版(兼容两列表长度不一致的场景)

如果需要处理长度不同的列表、同时收集所有差异位置,可以用如下实现:

def get_diff_positions(list1, list2, start_from_1: bool = True) -> list:
    diff_pos = []
    max_length = max(len(list1), len(list2))
    offset = 1 if start_from_1 else 0
    for index in range(max_length):
        v1 = list1[index] if index < len(list1) else None
        v2 = list2[index] if index < len(list2) else None
        if v1 != v2:
            diff_pos.append(index + offset)
    return diff_pos

# 测试调用
print(get_diff_positions(l1, l2))
# 输出:[4]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:54:08