How to compute a delta: the difference between lists of strings

Emile van Sebille emile at fenx.com
Sat May 5 11:50:23 EDT 2012


On 5/5/2012 5:12 AM J. Mwebaze said...
> This is out of curiosity, i know this can be done with python diffllib
> module, but been figuring out how to compute the delta, Consider two
> lists below.
>
> s1 = ['e', 'f', 'g', 'A', 'B', 'C', 'D', 'C']
> s2 =['e', 'A', 'B', 'f', 'g', 'C', 'D', 'z']
>
> This is the result should be
>
> ['  e', '+ A', '+ B', '  f', '  g', '- A', '- B', '  C', '  D', '- C',
> '+ z']
>
> ideas on how to approach this.. ?
>

use difflib:

from difflib import unified_diff as ud

s1 = ['e', 'f', 'g', 'A', 'B', 'C', 'D', 'C']
s2 = ['e', 'A', 'B', 'f', 'g', 'C', 'D', 'z']

[ r for r in ud(s1,s2,lineterm="|") if not r.endswith("|") ]

HTH,

Emile




More information about the Python-list mailing list