ayaan
ayaan

Reputation: 735

how can we compare two lists which are in two different files?

I'm new to python and I'm using python 2.7.6. In my program I've to compare two lists which are in two different files like the ones below:

list1=[1,2,3,4,5,6,7,8,9,10] #this list is in file 'a.txt'
list2=[2,4,6,8,10] #this list in file 'b.txt"
diff = difflib.ndiff(open('a.txt').readlines(),open('b.txt').readlines())

I used difflib but I'm not getting the correct output

How do I compare these two list and print out the differences?

Upvotes: 1

Views: 1995

Answers (1)

Deck
Deck

Reputation: 1979

If you want to get values which are only in one list you can use set difference operation.

>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list2=[2,4,6,8,10]
>>> set(list1) - set(list2)
set([1, 3, 9, 5, 7])

How to read the lists from file is another question. It depends on format of the files, what delimiter you use. Assuming that you have a file with one item per line:

data1 = [int(line.strip()) for line in open("a.txt", 'r')]
data2 = [int(line.strip()) for line in open("b.txt", 'r')]
res = list((set(data1) - set(data2)).union(set(data2) - set(data1)))

You pointed in the comment that file contains one line with values separated by commas, so:

data1 = open("a.txt", 'r').readline().strip().split(',')
data2 = open("b.txt", 'r').readline().strip().split(',')
res = list((set(data1) - set(data2)).union(set(data2) - set(data1)))

Upvotes: 2

Related Questions