简体   繁体   中英

Trying to remove multiples of the same number in Python

I'm trying to remove numbers from a list that are the same. So if I have 1,2,3,4,5,3 and I tell it to remove 3, it will only remove the first one (using .remove) to give me 1,2,4,5,3. I now know that .remove is only supposed to remove the first one, so my question is, what other method can I use? I've tried .pop and del but neither seem to do all of them (though I could have been doing it wrong). I would have just made a new list without the repeating number but it's meant to go through my teachers driver so I can't just make up a new list (or at least, I'm assuming there's any easier way?) In case it helps, here's that part of the code so far:

    def remove_element(self,integer):
        self.integer = integer
        self.members.remove(integer)

You could use the built-in filter , and you don't have to write a method for it:

>>> l = [1, 2, 3, 4, 5, 3]
>>> filter(lambda f: f != 3, l)
[1, 2, 4, 5]

In the code above, we define a lambda function lambda f: f != 3 , which test if an element in the list is 3 or not. In your case, you might use self.integer to replace 3 .

If you are not familiar with lambda function, lambda f: f != 3 is equivalent to the function foo :

>>> def foo(f):
...     return f != 3

You can use a list comprehension :

>>> l = [1,2,3,4,5,3]
>>> 
>>> [i for i in l if i != 3]
[1, 2, 4, 5]

Just remember that this doesn't actually modify l but instead creates a new list, so be sure to reassign l to the result of the comprehension.

list comprehension , eg:

[x for x in a_list if x != integer]

So in your case it would be:

def remove_element(self,integer):
    self.integer = integer
    self.members = [elem for elem in self.members if elem != integer]
def without_element(l, element):
    return [item for item in l if item != element]

def remove_all(l, element):
    try:
        while True:
            l.remove(element)
    except ValueError:
        pass

The first function makes a new list without any copies of the element you don't want. The second removes all copies from the existing list. There's no "remove all copies" method; usually, if you want that, you're using the wrong data structure. Are you sure you should be using a list?

def remove_element(self,integer):
    while integer in self.members:
          self.members.remove(integer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM