-1

Given a list of objects that look vaguely like the following pseudocode:

class myObj:
    self.init(i, s):
        myInt = i
        myString = j

And we pseudocode lists, one of them with the important properties like this:

Mario = [MyObj(0, 'foo1'), MyObj(0, 'foo2'), MyObj(0, 'foo3')]
Luigi = ['bar1', bar2']

Then we try to remove any of MyObj from Mario that does not match a string in Luigi:

for coin in Mario:
    if coin.myString not in Luigi:
        Mario.remove(coin)

Problem is, this only loops twice, then exits, with len(Mario) == 1, instead of zero.

using

Peach = [(myObj)x for x.myString in Mario if x not in Luigi]

errors with: "[" was not closed

How can I compare the strings in Luigi to all of Mario's myStrings, and discard the objects that do not fit?

I checked the following SO questions, and none helped: Remove all values within one list from another list?

Comparing list of objects to a string

Remove all the elements that occur in one list from another

1
  • What do you expect (myObj)x and for x.myString in ... to do? This is not valid syntax. Commented Jan 7, 2022 at 17:02

1 Answer 1

0

So, I had been struggling with this for like 2 days, and as I was typing it out, a solution came to me.

If I use List Comprehension, I can do the following:

    Peach = [coin for coin in Mario if coin.myString in Luigi]

This returns the correct objects, and it looks like it preserves ordering, too.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.