1

鉴于这两个列表

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

除了第 4 个元素外,它们是相同的。我需要一个代码来检测这两组之间的差异并打印出检测到的差异的位置。在这种情况下,它将是 = 4。andintersection命令union不起作用,因为它们没有考虑索引。

我试过这段代码,但它没有打印出任何东西:

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

for i in l1:
    if i != l2[l1.index(i)]:
        print(l1.index(i),i)
4

3 回答 3

1

您的代码不起作用,因为list.index(value [, pos])仅报告该列表中值的第一次出现 [after ]pos

这将报告差异:

l1=[0,0,0,0,1,1,1,1]
l2=[0,0,0,1,1,1,1,1]
print(*(p for p,v in enumerate(zip(l1,l2)) if v[0]^v[1]))

输出:

3

zip(..)值按位置配对到元组中,enumerate(..)获取index, tuple值并且v[0]^v[1]是逻辑异或,仅当值至少相差 1 位时才为真。

看:


这个更简单的版本没有 zip:

for index,number in enumerate(l1): # get index & number of one list
    if l2[index] != number:        # compare to other number
        print(f"On {index}: {number} != {l2[index]}")
于 2021-11-30T21:04:48.867 回答
0

你可以使用邮编

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

diff_idx = [idx for idx,(x,y) in enumerate(zip(l1,l2)) if x != y]
print(diff_idx)

输出

[3]
于 2021-11-30T21:06:40.033 回答
-2
l1=[0,0,0,0,1,1,1,1]
l2=[0,0,0,1,1,1,1,1]
print(l1.index(l1 != l2))

第三行返回不满足条件 l1 不等于 l2 的 l1 的索引位置。

于 2021-11-30T21:11:24.067 回答