Remove the first N items that match a condition in a Python list

后端 未结 7 1099
余生分开走
余生分开走 2021-01-30 20:11

If I have a function matchCondition(x), how can I remove the first n items in a Python list that match that condition?

One solution is to itera

7条回答
  •  梦毁少年i
    2021-01-30 20:41

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can use and increment a variable within a list comprehension:

    # items = [1, 10, 2, 9, 3, 8, 4, 7]
    total = 0
    [x for x in items if not (x < 5 and (total := total + 1) <= 3)]
    # [10, 9, 8, 4, 7]
    

    This:

    • Initializes a variable total to 0 which will symbolize the number of previously matched occurrences within the list comprehension
    • Checks for each item if it both:
      • matches the exclusion condition (x < 5)
      • and if we've not already discarded more than the number of items we wanted to filter out by:
        • incrementing total (total := total + 1) via an assignment expression
        • and at the same time comparing the new value of total to the max number of items to discard (3)

提交回复
热议问题