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

4

11

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']
Reata answered 2/8, 2016 at 18:43 Comment(3)
This is like a set intersection (truncated), although sets don't have order.Arni
Note that using the order while 5>len(work) is seen illogical by many, leading to the name of "yoda conditions". It's correct either way of course:)Subeditor
@WilliamCorrigan You should accept the answer you found helpful to indicate to other readers what helped solve your problem.Expansile
S
8

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.

Spinet answered 2/8, 2016 at 18:46 Comment(3)
More optimal and clearer than my solution. I deleted mine to make sure yours was clearly seen as the favoured solution. +1Expansile
@Expansile thank you very much ! It wasn't needed to delete your answer :)Spinet
For this case, I liked your solution much more than mine and hope the OP sees the same. :)Expansile
P
1

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.

Polyanthus answered 2/8, 2016 at 18:52 Comment(0)
S
1

Alternatively, to stay a little closer to your original logic:

i = 0
while 4 > len(work) and i < len(it):
    nope = it[i]
    if nope in does:
        work.append(nope)
    i += 1

# ['my', 'mother', 'told', 'me', 'to']
Supplement answered 2/8, 2016 at 18:53 Comment(0)
M
0

Just for fun, here's a one-liner with no imports:

does = ['my', 'mother', 'told', 'me', 'to', 'choose', 'the']
it = ['my', 'mother', 'told', 'me', 'to', 'choose', 'the']
work = [match for match, _ in zip((nope for nope in does if nope in it), range(4))]
Mesomorphic answered 1/10, 2016 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.