Given a list of values remove first occurrence

2020-04-11 12:05发布

问题:

def drop dest(routes,location):
    for i in range(len(routes)):
        if routes[i] == location:
              routes.remove(routes[i])
    return routes

I am using a function definition given a list as
routes = [(3,2),(2,4),(5,5),(2,4)], and say I just want to remove the first occurrence value of (2,4). I am a little confused in how to do this because I do remove the value but I also remove the other value given. Where I just want to remove the first given value.

回答1:

It's simple, use list.remove.

>>> routes = [(3,2),(2,4),(5,5),(2,4)]
>>> routes.remove((2,4))
>>> routes
[(3, 2), (5, 5), (2, 4)]


回答2:

if that is your code and needs to be in a loop and removed only once I would do it like that:

def drop_dest(routes,location):
     flag = 1
     for i in range(len(routes)):
          if routes[i] == location and flag == 1:
              routes.remove(routes[i])
              flag = 0
     return routes´