Shankar
Shankar

Reputation: 3624

Mapping two list of lists based on its items into list pairs in Python

I have two list of lists which basically need to be mapped to each other based on their matching items (list). The output is a list of pairs that were mapped. When the list to be mapped is of length one, we can look for direct matches in the other list. The problem arises, when the list to be mapped is of length > 1 where I need to find, if the list in A is a subset of B.

Input:

A = [['point'], ['point', 'floating']]
B = [['floating', 'undefined', 'point'], ['point']]

My failed Code:

C = []
for a in A:
    for b in B:
        if a == b:
            C.append([a, b])
        else:
            if set(a).intersection(b):
                C.append([a, b])

print C

Expected Output:

C = [
     [['point'], ['point']], 
     [['point', 'floating'], ['floating', 'undefined', 'point']]
    ]

Upvotes: 0

Views: 143

Answers (2)

James Holderness
James Holderness

Reputation: 23001

Just for interests sake, here's a "one line" implementation using itertools.ifilter.

from itertools import ifilter

C = list(ifilter(
  lambda x: x[0] == x[1] if len(x[0]) == 1 else set(x[0]).issubset(x[1]),
  ([a,b] for a in A for b in B)
))

EDIT:

Having reading the most recent comments on the question, I think I may have misinterpreted what exactly is considered to be a match. In which case, something like this may be more appropriate.

C = list(ifilter(
  lambda x: x[0] == x[1] if len(x[0])<2 or len(x[1])<2 else set(x[0]).intersection(x[1]),
  ([a,b] for a in A for b in B)
))

Either way, the basic concept is the same. Just change the condition in the lamba to match exactly what you want to match.

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

Just add a length condition to the elif statement:

import pprint
A = [['point'], ['point', 'floating']]
B = [['floating', 'undefined', 'point'], ['point']]
C = []

for a in A:
    for b in B:
        if a==b:
            C.append([a,b])
        elif all (len(x)>=2 for x in [a,b]) and not set(a).isdisjoint(b):
            C.append([a,b])

pprint.pprint(C)

output:

[[['point'], ['point']],
 [['point', 'floating'], ['floating', 'undefined', 'point']]]

Upvotes: 1

Related Questions