Protoss Reed
Protoss Reed

Reputation: 265

Python: Compare elements in two list by pair

I am so sorry for asking so silly question. So I have got two lists(columns) for instance:

In:
a= [0.0,1.0,2.0,3.0,4.0]
b= [1.0,2.0,3.0,5.0,6.0]
zp = list(zip(a,b)) #And I zipped it for better view.
for i in zp:
    print (i)

Out:
(0.0, 1.0)
(1.0, 2.0)
(2.0, 3.0)
(3.0, 5.0)
(4.0, 6.0)

I would like compare each i[1] with each i[0] in the next pair(tuple) For example:

1st pair i[1] = 1.0 compare with i[0] in 2nd
2nd pair i[0] = 1.0 compare with i[0] in 3rd
etc

I would like find difference in pair.

If i[1] != i[0] 
  print this value 

Answer is 5.0 & 4.0

Thank you for your attention

Upvotes: 0

Views: 4231

Answers (2)

Ari Gold
Ari Gold

Reputation: 1548

index variant without zip and enumerate

a = [0.0,1.0,2.0,3.0,4.0]
b = [1.0,2.0,3.0,5.0,6.0]

for i in a:
    if a.index(i) and i != b[a.index(i)-1]:
       print "{0} > {1}".format(i, b[a.index(i)-1])

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78556

The initial zip for better view is not completely necessary.

You could simply zip a slice of a starting from index 1 with b, and then compare the items using a for loop:

a = [0.0,1.0,2.0,3.0,4.0]
b = [1.0,2.0,3.0,5.0,6.0]

for i, j in zip(a[1:], b):
    if i != j:
        print(j, i)
#            5.0, 4.0

Upvotes: 4

Related Questions