Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning string matches between two lists for a given number of elements in a third list

I've got a feeling that I will be told to go to the 'beginner's guide' or what have you but I have this code here that goes

does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []

while 5 > len(work):
    for nope in it:
        if nope in does:
            work.append(nope)

print (work)

And I get

['my', 'mother', 'told', 'me', 'to', 'choose', 'the']

Why is this? And how do I convince it to return

['my', 'mother', 'told', 'me']
like image 300
William Corrigan Avatar asked Aug 02 '16 18:08

William Corrigan


People also ask

How do you match a value between 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.

How do you compare two lists and add the difference to a third list in Python?

Method 3: Use a list comprehension and set to Find the Difference Between Two Lists in Python. In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator.

How do you find the similarity between two lists in Python?

The method which is formally applied to calculate the similarity among lists is finding the distinct elements and also common elements and computing it's quotient. The result is then multiplied by 100, to get the percentage.


2 Answers

You could try something like this:

for nope in it:
   if len(work) < 5 and nope in does:
       work.append(nope)
   else:
       break

The problem with your code is that it does the check of the work's length, after having looped through all the items of it and having added all of them that are in does.

like image 130
Christos Avatar answered Nov 04 '22 08:11

Christos


You can do:

does = ['my','mother','told','me','to','choose','the']
it = ['my','mother','told','me','to','choose','the']
work = []
for nope in it:
    if nope in does:
        work.append(nope)
work = work[:4]
print (work)

It's just making the list without checking the length, then cutting it and leaving only the 4 first elements.

like image 43
Yotam Salmon Avatar answered Nov 04 '22 07:11

Yotam Salmon