Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two lists in Python

So to give a rough example without any code written for it yet, I'm curious on how I would be able to figure out what both lists have in common.

Example:

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

I'd like to be able to return:

['a', 'c']

How so?

Possibly with variable strings like:

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

And return:

'I love yellow and'
like image 858
Matthew Avatar asked Jul 28 '12 02:07

Matthew


People also ask

How do you compare two lists in Python?

We can club the Python sort() method with the == operator to compare two lists. Python sort() method is used to sort the input lists with a purpose that if the two input lists are equal, then the elements would reside at the same index positions.

What is == comparing in Python?

The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .


2 Answers

Use set intersection 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 into a string.

--

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

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

For a case where the list aren't the same length, with the result as specified 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']
like image 93
Levon Avatar answered Oct 20 '22 00:10

Levon


i think this is what u want ask me anything about it i will try to answer it

    listA = ['a', 'b', 'c']
listB = ['a', 'h', 'c']
new1=[]
for a in listA:
    if a in listB:
        new1.append(a)

john = 'I love yellow and green'
mary = 'I love yellow and red'
j=john.split()
m=mary.split()
new2 = []
for a in j:
    if a in m:
        new2.append(a)
x = " ".join(new2)
print(x)
like image 29
Margouma Saleh Avatar answered Oct 20 '22 00:10

Margouma Saleh