given these two lists
l1=[0,0,0,0,1,1,1,1]
l2=[0,0,0,1,1,1,1,1]
they are identical except for the 4th element. I need a code that detects the difference between these two sets and prints out the location of the detected difference. In this case it would be = 4.
The intersection
and union
command wouldn't work as they don't take the index into consideration.
I have tried this code, but it does not print out anything:
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)
CodePudding user response:
Your code does not work because list.index(value [, pos])
only reports the first occurence of a value in that list [after pos
].
This would report the differences:
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]))
Output:
3
The zip(..)
pairs up values positionally in to tuples, enumerate(..)
gets the index, tuple
value and v[0]^v[1]
is a logical xor that is only true if the values differ at least in 1 bit.
See:
The simpler version of this works without 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]}")
CodePudding user response:
output = [idx for idx,(i,j) in enumerate(zip(l1,l2), start=1) if i!=j]
print(output) # [4]
Or you can do:
for i in range(len(l1)):
if l1[i] != l2[i]:
print(i 1)
which is closer to what you wrote.
CodePudding user response:
You can use zip
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)
output
[3]
CodePudding user response:
l1=[0,0,0,0,1,1,1,1]
l2=[0,0,0,1,1,1,1,1]
print(l1.index(l1 != l2))
The third line returns the index position of l1 which does not satisfy the condition l1 not equal to l2.