Intersection between nesten loops in specific row

Viewed 26

I want to know how to find the intersection from the first entry in each sublist, and concatenate the two sublists with the last entry. In this example the output should be:

I have two nested lists:

list1 = [[123, Harold, 5], [321, John, 3], [222, John, 2]]

list2 = [[333, James, 3], [123, Harold, 6], [999, John, 2]]

OUTPUT: intersect_list = [[123, Harold, 5, 6]]

Is this possible without using pandas? And how? :-) Thank you!

Right now, I can only find full intersection (the whole sublist), but not only the first entry and then concatenating the last entry.

intersectionList = [value for value in list1 if value in list2]

Kind regards, Anders

1 Answers

from your exemple, 6 is not in the intersection, but is in the output, so a valid answer should be:

list1 = [[123, 'Harold', 5], [321, 'John', 3], [222, 'John', 2]]
list2 = [[333, 'James', 3], [123, 'Harold', 6], [999, 'John', 2]]
result = []
for sublist1 in list1:
    for sublist2 in list2:
        for item2 in sublist2:
            if item2 in sublist1:
                result+= [list(set(sublist1+sublist2))]
print(result)

this will lead to some duplicates, wich you will have to work on:

[['Harold', 123, 5, 6], ['Harold', 123, 5, 6], [3, 321, 'John', 333, 'James'], [3, 321, 2, 'John', 999], [2, 'John', 222, 999], [2, 'John', 222, 999]]

if you want only the intersection:

list1 = [[123, 'Harold', 5], [321, 'John', 3], [222, 'John', 2]]
list2 = [[333, 'James', 3], [123, 'Harold', 6], [999, 'John', 2]]
result = []
for sublist1 in list1:
    for sublist2 in list2:
        for item2 in sublist2:
            if item2 in sublist1 and not (item2 in result):
                result+= [item2]
print(result)

which will give:

[123, 'Harold', 3, 'John', 2]
Related