XORing two lists

John La Rooy nospampls.jlr at doctor.com
Tue Feb 18 19:20:47 EST 2003


Boris Genz wrote:

> Hello Guys...
> I am making my second ( hehe, yeah second, I'm a real newb, but I'm trying
> really hard ) python program and I have small problems. I have two text
> files, in each I have a list ( of numbers ) written ( with pickle command,
> because I want it to be a list after saving it to file and loading it back
> to program )... What I want for my program to do is to read the
> information from both text files, retreive the lists from them, and make
> XOR operation with each number from my list. So for example, in file
> test1.txt I have a following list: [1234, 65477, 44412, 2214]
> and in the second file called test2.txt I have something like this:
> [78974, 2221, 4447]
> I want to get a list with following numbers ( I XORed each pair of the
> numbers manually. The last number is the same, because it doesn't have its
> pair ):
> [77996,63336,48163,2214]
> Can you tell me how to do this...
> I would really appreciate your help.
> Thanks in advance.
> Boris


 >>> L1=[1234, 65477, 44412, 2214]
 >>> L2=[78974, 2221, 4447]

### This would work if the lists were equal length. It causes an
### exception if L2 is longer than L1. You can use this if you
### first pad the shorter list with 0's
 >>> map(int.__xor__,L1,L2)
[77996, 63336, 48163, NotImplemented]

 >>> map(lambda x,y: (x or 0) ^ (y or 0),L1,L2)
[77996, 63336, 48163, 2214]

John





More information about the Python-list mailing list