Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find match items from two lists? [duplicate]

Tags:

Possible Duplicate:
Python: How to find list intersection?

I have two lists of data in a .txt

data1 = "name1", "name2", "name3", "name4" etc.

data2 = "name3", "name6", "name10" etc.

I want to find out which names appears in both list How would I do it?

like image 557
ivanhoifung Avatar asked Jul 23 '12 14:07

ivanhoifung


People also ask

How do you find the matching element in two lists in Python?

To compare two lists and return matches with Python, we can use the set's intersection method. We have 2 lists a and b that we want to get the intersection between. To do this, we convert a to a set with set . Then we call intersection with b and assign the intersection of a and b to intersection`.

How do I compare two lists of data in Python?

The cmp() function is a built-in method in Python used to compare the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1.

How do you find the common values of two lists in Python?

Method 2:Using Set's intersection property Convert the list to set by conversion. Use the intersection function to check if both sets have any elements in common. If they have many elements in common, then print the intersection of both sets.


1 Answers

Use sets:

set(data1) & set(data2)

The & operator means "give me the intersection of these two sets"; alternatively you can use the .intersection method:

set(data1).intersection(data2)
like image 139
Martijn Pieters Avatar answered Sep 28 '22 03:09

Martijn Pieters