Home > OS >  Compare 2 list and get diffrence
Compare 2 list and get diffrence

Time:11-22

I have 2 two dimensional arrays as

Here the 0th index is the id and 1st index is the value for that id

I want to compare 2 lists and get the ids which have diffrent value in list2

list1 = [[1,0], [2,1], [3,0]] #[[id, value]]
list2 = [[1,1], [2,1], [3,1]] #[[id, value]]

getDiffrence(list1, list2)
#should return
[1, 3]

Because in the above example 1 and 3 are the only ids which value is different in list2 in compare to list1

CodePudding user response:

If the order is always the same as in your example, you can simply zip the lists and compare the values:

differences = []
for (key1, value1), (key2, value2) in zip(list1, list2):
    if value1 != value2:
        differences.append(key1)

If they are not in the same order, you'll be better off converting them to dicts first:

dict1 = dict(list1)
dict2 = dict(list2)

differences = [key for key, value in dict1.items() if dict2[key] != value]

CodePudding user response:

I would do it following way

list1 = [[1,0], [2,1], [3,0]]
list2 = [[1,1], [2,1], [3,1]]
list1 = [tuple(i) for i in list1]
list2 = [tuple(i) for i in list2]
ids = set(i[0] for i in set(list1).symmetric_difference(list2))
print(ids)

output

{1, 3}

Explanation: I first convert internal lists into tuples as you can not have set of lists (as they are mutable). Then use set arithmetic to detect tuples present in exactly one of lists, then retrieve first element of each such tuple and made set of it to remove duplicates. Note: ids is set, you might elect to convert it to list (ids=list(ids)) or sorted list (ids=sorted(ids)) if your requirements dictate so.

CodePudding user response:

def getDiffrence(list1, list2):

    diffs=[]

    for el in list1:
        id_=el[0]
        list2_same_id=[e for e in list2 if e[0]==id_]
        if len(list2_same_id)>0:
            if el[1]!=list2_same_id[0][1]:
                diffs.append(id_)
                
    return diffs

I agree with Tomerikoo:

If the order is always the same as in your example, you can simply zip the lists and compare the values:

CodePudding user response:

I assumed that lists will have the same id for the same position, and that id is on position 0 of the array and value on position 1.
I came up with the code:

def getDiff(list1, list2):
    result = []
    for i in range(len(list1)):
        if list1[i][1] != list2[i][1]:
            result.append(list1[i][0])

    return result
  • Related