I recently needed to show changes in the ordering of two lists in a way that makes sense to a person. Python's difflib makes this ridiculously easy. This little snippet does the trick:
import difflib
def showDiffs(old, new):
''' Show differences between two lists '''
diffs = difflib.SequenceMatcher(None, old, new).get_matching_blocks()
rowFormat = '%-10s %s'
oldCurrent = newCurrent = 0
for oldIx, newIx, count in diffs:
while oldCurrent < oldIx:
print rowFormat % (old[oldCurrent], '')
oldCurrent += 1
while newCurrent < newIx:
print rowFormat % ('', new[newCurrent])
newCurrent += 1
for i in range(count):
print rowFormat % (old[oldIx+i], new[newIx+i])
oldCurrent = oldIx + count
newCurrent = newIx + count
Now showDiffs( [1,3,2,4], [1,2,3,4] ) prints out
1 1
2
3 3
2
4 4
Sweet!
|