TAGS :Viewed: 15 - Published at: a few seconds ago
[ Merging nested lists with overlap ]
I have to merge nested lists which have an overlap. I keep thinking that there has to be an intelligent solution using list comprehensions and probably difflib, but I can't figure out how it should work. My lists look like this:
[['C', 'x', 'F'], ['A', 'D', 'E']]
and
[['x', 'F', 'G', 'x'], ['D', 'E', 'H', 'J']].
They are above another, like rows in a matrix. Therefore, they have overlap (in the form of
[['x', 'F'], ['D', 'E']]).
A merge should yield:
[['C', 'x', 'F', 'G', 'x'], ['A', 'D', 'E', 'H', 'J']].
How can I achieve this?
Answer 1
You can try something like this.
list1 = [['C', 'x', 'F'], ['A', 'D', 'E']]
list2 = [['x', 'F', 'G', 'x'], ['D', 'E', 'H', 'J']]
for x in range(len(list1)):
for element in list2[x]:
if element not in list1[x]:
list1[x].append(element)
print list1[x]
Output:
['C', 'x', 'F', 'G']
['A', 'D', 'E', 'H', 'J']
I hope this helps you.