Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - simple way to join 2 arrays/lists based on common values

I have tried for a while but can't find a simple way to join 2 lists or arrays based only on common values. Similar to an SQL inner join but with arrays/lists and not dict, or some other data type. eg.

a = [1, 2, 3]
b = [2, 3, 4]
join(a, b)

prints

[2, 3]

seems so simple but lacking from python or numpy.

like image 516
Jacques MALAPRADE Avatar asked Feb 05 '15 08:02

Jacques MALAPRADE


People also ask

How do you find the common values between 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.

How do you combine lists within a list Python?

Use the sum() function to concatenate nested lists to a single list by passing an empty list as a second argument to it.

How can you join two lists lst1 and lst2?

defaultdict and traverse through 'lst1'+'lst2' and append the first element of 'lst1' as key and tupled second element of both respective sublists as value. Finally, we traverse through 'dict1' and initialize 'dictlist' with the desired output.


1 Answers

Probably a duplicate, but in case it is not:

>>> a = [1,2,3]
>>> b = [2,3,4]
>>> list(set(a) & set(b))
[2, 3]

For large lists (external data), see this S.O. answer.

like image 194
Ray Toal Avatar answered Nov 15 '22 20:11

Ray Toal