Comparing two lists in Python

So, to give an approximate example without code written for it, I wonder how I can figure out what both lists have in common.

Example:

listA = ['a', 'b', 'c'] listB = ['a', 'h', 'c'] 

I would like to be able to return:

 ['a', 'c'] 

How it is?

Perhaps with variable strings like:

 john = 'I love yellow and green' mary = 'I love yellow and red' 

And return:

 'I love yellow and' 
+6
source share
3 answers

Use the intersection set for this:

 list(set(listA) & set(listB)) 

gives:

 ['a', 'c'] 

Note that since we are dealing with sets, this may not preserve order:

 ' '.join(list(set(john.split()) & set(mary.split()))) 'I and love yellow' 

using join() to convert the resulting list to a string.

-

For your example / comment below, this will keep order (inspired by the comment from @DSM)

 ' '.join([j for j, m in zip(john.split(), mary.split()) if j==m]) 'I love yellow and' 

In the case where the list does not have the same length, with the result indicated in the comment below:

 aa = ['a', 'b', 'c'] bb = ['c', 'b', 'd', 'a'] [a for a, b in zip(aa, bb) if a==b] ['b'] 
+16
source

If two lists are the same length, you can iterate side by side, for example:

 list_common = [] for a, b in zip(list_a, list_b): if a == b: list_common.append(a) 
+2
source

Cross them as many:

 set(listA) & set(listB) 
+1
source

Source: https://habr.com/ru/post/921542/


All Articles