Home > Net >  Is there better way to erase elements not in common in nested lists
Is there better way to erase elements not in common in nested lists

Time:04-30

I tried to compare two nested lists like this shape:
l1 = [[1,'a'],[2,'a'],[3,'a'],[5,'a']]
l2 = [[1,'b'],[2,'b'],[4,'b'],[5,'b']].
And I need to get lists like this:
l1 = [[1, 'a'], [2, 'a'], [5, 'a']],
l2 = [[1, 'b'], [2, 'b'], [5, 'b']].
I could implement it in this way:

def validation_in_list(lst1,lst2,idx=0):
    lst1_val = lst1[:]
    lst2_val = lst2[:]
    lst1_idx = []
    lst2_idx = []
    for element in lst1:
        lst1_idx  = [element[idx]]
    for element in lst2:
        lst2_idx  = [element[idx]]
    set1 = set(lst1_idx)
    set2 = set(lst2_idx)
    del1 = set1.difference(set2)
    del2 = set2.difference(set1)
    for i in range(len(lst1)):
        if lst1[i][idx] in del1:
            lst1_val.remove(lst1[i])
    for i in range(len(lst2)):
        if lst2[i][idx] in del2:
            lst2_val.remove(lst2[i])
    return [lst1_val,lst2_val]

Is there any better way to make it? (like faster, or shorter)

CodePudding user response:

One possible solution is that you can create a temporary set that contains intersection between l1 and l2 elements and then filter l1 and l2 according this set:

l1 = [[1, "a"], [2, "a"], [3, "a"], [5, "a"]]
l2 = [[1, "b"], [2, "b"], [4, "b"], [5, "b"]]

tmp = set(v for v, _ in l1).intersection(v for v, _ in l2)

l1 = [subl for subl in l1 if subl[0] in tmp]
l2 = [subl for subl in l2 if subl[0] in tmp]

print(l1)
print(l2)

Prints:

[[1, 'a'], [2, 'a'], [5, 'a']]
[[1, 'b'], [2, 'b'], [5, 'b']]

CodePudding user response:

you could also create intermediate dictionaries d1 and d2 and then re-create the lists from there:

d1 = {k: v for k, v in l1}
d2 = {k: v for k, v in l2}

l1 = [[k, v] for k, v in d1.items() if k in d2]
l2 = [[k, v] for k, v in d2.items() if k in d1]
  • Related