Home > front end >  Element Commun IN Double List PYTHON
Element Commun IN Double List PYTHON

Time:07-07

I have two list of list and I want to check what element of l1 is not in l2 and add all this element in a new list ls in l2. For example,

input:
l1 = [[1,2,3],[5,6],[7,8,9,10]]
l2 = [[1,8,10],[3,9],[5,6]]

output:
l2 = [[1,8,10],[3,9],[5,6],[2,7]]

I write this code but it is seem doesn't work...

ls = []
for i in range(len(l1)):
  for j in range(len(l1[i])):
    if l1[i][j] not in l2 and l1[i][j] not in ls:
      ls.append(l1[i][j])
l2.append(ls)

I code this in python. Any ideas where can be the problem ?

CodePudding user response:

This should work:

l1 = [[1,2,3],[5,6],[7,8,9,10]]
l2 = [[1,8,10],[3,9],[5,6]]

l1n = set([x for xs in l1 for x in xs])
l2n = set([x for xs in l2 for x in xs])

l2.append(list(l1n - l2n))

CodePudding user response:

You are checking whether the elements are in l2, not if they are in any of the sublists of l2. First, you should probably create a set from all the elements in all the sublists of l2 to make that check faster. Then you can create a similar list comprehension on l1 to get all the elements that are not in that set. Finally, add that to l2 or create a new list.

>>> l1 = [[1,2,3],[5,6],[7,8,9,10]] 
>>> l2 = [[1,8,10],[3,9],[5,6]]                                             
>>> s2 = {x for lst in l2 for x in lst}                                     
>>> [x for lst in l1 for x in lst if x not in s2]                           
[2, 7]
>>> l2   [_]                                                                
[[1, 8, 10], [3, 9], [5, 6], [2, 7]]

CodePudding user response:

May be you can try like this also

import itertools

#MERGE LIST1
l1 = [[1,2,3],[5,6],[7,8,9,10]]
merged = list(itertools.chain(*l1))

#MERGE LIST2
l2 = [[1,8,10],[3,9],[5,6]]
merged2 = list(itertools.chain(*l2))

#FIND THE ELEMENTS NOT IN SECOND LIST
newlist =  [item for item in merged if item not in merged2]

#APPEND THE NEWLIST TO LIST2
l2.append(newlist)

print(l2)
  • Related