Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding intersection of two lists of strings in python

I have gone through Find intersection of two lists?, Intersection of Two Lists Of Strings, Getting intersection of two lists in python. However, I could not solve this problem of finding intersection between two string lists using Python.

I have two variables.

A = [['11@N3'], ['23@N0'], ['62@N0'], ['99@N0'], ['47@N7']]

B  = [['23@N0'], ['12@N1']]

How to find that '23@N0' is a part of both A and B?

I tried using intersect(a,b) as mentioned in http://www.saltycrane.com/blog/2008/01/how-to-find-intersection-and-union-of/ But, when I try to convert A into set, it throws an error:

File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'

To convert this into a set, I used the method in TypeError: unhashable type: 'list' when using built-in set function where the list can be converted using

result = sorted(set(map(tuple, A)), reverse=True)

into a tuple and then the tuple can be converted into a set. However, this returns a null set as the intersection.

Can you help me find the intersection?

like image 311
Sharath Chandra Avatar asked Feb 24 '15 08:02

Sharath Chandra


People also ask

Can you intersect lists in python?

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists.

How do I compare two lists to find differences in python?

The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .


2 Answers

You can use flatten function of compiler.ast module to flatten your sub-list and then apply set intersection like this

from compiler.ast import flatten

A=[['11@N3'], ['23@N0'], ['62@N0'], ['99@N0'], ['47@N7']]
B=[['23@N0'], ['12@N1']]

a = flatten(A)
b = flatten(B)
common_elements = list(set(a).intersection(set(b)))
common_elements
['23@N0']
like image 103
Anurag Sharma Avatar answered Nov 06 '22 00:11

Anurag Sharma


The problem is that your lists contain sublists so they cannot be converted to sets. Try this:

A=[['11@N3'], ['23@N0'], ['62@N0'], ['99@N0'], ['47@N7']]
B=[['23@N0'], ['12@N1']]

C = [item for sublist in A for item in sublist]
D = [item for sublist in B for item in sublist]

print set(C).intersection(set(D))
like image 39
igavriil Avatar answered Nov 05 '22 23:11

igavriil