Search code examples
pythonlistcomparison

Two lists comparison with replacing elements Python


I have some configuration file named file1 with row:

if [data] in [ "data01", "data02", "data03" ] {

and another file named file2 with rows:


dATa02
datA03

dAta04

From file1 I'm using regular expression for pasring data from row: if [data] in [ "data01", "data02", "data03" ] {

import re
with open('/file1', 'r') as f:
    for l in f:
        l_s = row.strip()
        if 'if [data] in ' in row_s:
            data1 = re.findall('"(.\w+)\"*', l_s)
            print(data1)

As a result I get a list data1: [ 'data01', 'data02", 'data03' ]

From file2 I'm parsing data with skipping empty rows and making an elements lowercase:

with open('/file2', 'r') as f:
    data2 = [l.lower() for l in (line.strip() for line in f) if l]
    print(data2)

As a result I get a anouther list data2: [ 'data02', 'data03", 'data04' ]

I need to compare two lists data1 and data2 with adding new elements and deleting non-existing from data2 in data1. As a result, I what to know which elements were added/deleted.


Solution

  • Look into sets in python.

    added = set(data2) - set(data1) #data04
    deleted = set(data1) - set(data2) #data01