How to delete an item in a list if it exists?

前端 未结 7 911
無奈伤痛
無奈伤痛 2020-11-29 14:55

I am getting new_tag from a form text field with self.response.get(\"new_tag\") and selected_tags from checkbox fields with



        
相关标签:
7条回答
  • 2020-11-29 15:29

    Here's another one-liner approach to throw out there:

    next((some_list.pop(i) for i, l in enumerate(some_list) if l == thing), None)
    

    It doesn't create a list copy, doesn't make multiple passes through the list, doesn't require additional exception handling, and returns the matched object or None if there isn't a match. Only issue is that it makes for a long statement.

    In general, when looking for a one-liner solution that doesn't throw exceptions, next() is the way to go, since it's one of the few Python functions that supports a default argument.

    0 讨论(0)
提交回复
热议问题