0

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']]
    ]
8
  • Why [['point', 'floating'],['point']] is not in the expected output? Commented May 3, 2013 at 19:52
  • @ashwini See the explanation above. I have explained Y. Commented May 3, 2013 at 19:56
  • The length>2 (which you now updated) was bugging me, see my solution below. Commented May 3, 2013 at 20:09
  • @AshwiniChaudhary Sorry! that was a typo. Commented May 3, 2013 at 20:10
  • Why [['point'], ['floating', 'undefined', 'point']] is not in the expected output? Commented May 3, 2013 at 20:35

2 Answers 2

1

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']]]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.