-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

GokuMizuno
  • 493
  • 2
  • 5
  • 14

1 Answers1

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.

GokuMizuno
  • 493
  • 2
  • 5
  • 14