#47
2004-06-16 11:40:48
Fun with difflib
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 '''
# Get the diffs
diffs = difflib.SequenceMatcher(None, old, new).get_matching_blocks()
rowFormat = '%-10s %s'
oldCurrent = newCurrent = 0
for oldIx, newIx, count in diffs:
# Catch up the output to the current diff position
while oldCurrent < oldIx:
print rowFormat % (old[oldCurrent], '')
oldCurrent += 1
while newCurrent < newIx:
print rowFormat % ('', new[newCurrent])
newCurrent += 1
# Write the common sequence
for i in range(count):
print rowFormat % (old[oldIx+i], new[newIx+i])
# Update current locations
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!
Categories:
Python
|