Python|删除匹配某个条件的前 K 个元素
可以使用许多内置函数来删除列表中的元素。删除所有或仅删除一次出现的删除这两个函数都存在于Python库中。本文讨论仅删除与特定条件匹配的元素的前K个匹配项。
方法#1:朴素的方法
我们可以在元素出现K次后追加符合条件的元素,因此将执行类似于删除的任务。
# Python3 code to demonstrate
# to remove first K elements matching condition
# using Naive Method
# initializing list
test_list = [3, 5, 1, 6, 7, 9, 8, 5]
# printing original list
print ("The original list is : " + str(test_list))
# using Naive Method
# to remove first K elements matching condition
# removes first 4 odd occurrences
counter = 1
res = []
for i in test_list:
if counter > 4 or not (i % 2 != 0):
res.append(i)
else:
counter += 1
# printing result
print ("The filtered list is : " + str(res))
输出:
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : [6, 9, 8, 5]
方法#2:使用itertools.filterfalse() + itertools.count()
这是执行此特定任务的不同而优雅的方式。当计数器达到 K 并匹配条件时,它会过滤掉所有大于 K 的数字。这是完成此任务的单线和首选方法。
# Python3 code to demonstrate
# to remove first K elements matching condition
# using itertools.filterfalse() + itertools.count()
from itertools import filterfalse, count
# initializing list
test_list = [3, 5, 1, 6, 7, 9, 8, 5]
# printing original list
print ("The original list is : " + str(test_list))
# using itertools.filterfalse() + itertools.count()
# to remove first K elements matching condition
# removes first 4 odd occurrences
res = filterfalse(lambda i, counter = count(): i % 2 != 0 and
next(counter) < 4, test_list)
# printing result
print ("The filtered list is : " + str(list(res)))
输出:
The original list is : [3, 5, 1, 6, 7, 9, 8, 5]
The filtered list is : [6, 9, 8, 5]