如果列表应该就地过滤并且列表大小很大,那么前面的答案中提到的基于 list.remove() 的算法可能不合适,因为它们的计算复杂度是 O(n^2) . 在这种情况下,您可以使用以下 no-so pythonic 函数:
def filter_inplace(func, original_list):
""" Filters the original_list in-place.
Removes elements from the original_list for which func() returns False.
Algrithm's computational complexity is O(N), where N is the size
of the original_list.
"""
# Compact the list in-place.
new_list_size = 0
for item in original_list:
if func(item):
original_list[new_list_size] = item
new_list_size += 1
# Remove trailing items from the list.
tail_size = len(original_list) - new_list_size
while tail_size:
original_list.pop()
tail_size -= 1
a = [1, 2, 3, 4, 5, 6, 7]
# Remove even numbers from a in-place.
filter_inplace(lambda x: x & 1, a)
# Prints [1, 3, 5, 7]
print a
编辑:实际上,https ://stackoverflow.com/a/4639748/274937 的解决方案优于我的解决方案。它更pythonic并且工作得更快。所以,这是一个新的 filter_inplace() 实现:
def filter_inplace(func, original_list):
""" Filters the original_list inplace.
Removes elements from the original_list for which function returns False.
Algrithm's computational complexity is O(N), where N is the size
of the original_list.
"""
original_list[:] = [item for item in original_list if func(item)]