Kristofer
Kristofer

Reputation: 1487

How to XOR pairwise element in the same list

I have a list that is always binary. I want to XOR every two consequentive elements to satisfy a condition in a research paper. For instance: Given list=[1,0,1,1], XORing each consequtive pairs should be something like this: 1 XOR 0 = 1, 0 XOR 1 = 1, 1 XOR 1 = 0. To do so, is it correct to XOR two lists where the second list is the shifted verison of the original Something like: numpy.bitwise_xor([1,0,1,1],[0,1,0,1])?

Upvotes: 0

Views: 271

Answers (2)

percusse
percusse

Reputation: 3106

You can also use slices

>>> import numpy as np
>>> a = [1, 0, 1, 1]
>>> print np.bitwise_xor(a[1:], a[:-1])
array([1, 1, 0], dtype=int32)

Upvotes: 0

Sajid
Sajid

Reputation: 145

You can load the input list as an array (called a) and use numpy.roll to shift the array so that you now have another array (called b) which has stores the shifted array. Now bitwise_xor can be used on a,b.

 import numpy as np
 a = np.array([1,0,1,1])
 b= np.roll(a,len(a)-1)
 c = np.bitwise_xor(a,b)
 print(' A :',a,'\n','B :',b,'\n','C :',c)

Output:

 A : [1 0 1 1] 
 B : [0 1 1 1] 
 C : [1 1 0 0]

If you're using python 2.7, make sure the change the print statement!

Upvotes: 2

Related Questions