只需使用列表理解过滤掉不需要的项目:
a = [1, 2, 2, 3, 4, 5]
condition = lambda x: x > 2
b = [x for x in a if condition(x)] # b == [3, 4, 5]
a = [x for x in a if not condition(x)] # a == [1, 2, 2]
更新
如果您担心效率,那么这是另一种只扫描列表一次的方法:
def classify(iterable, condition):
""" Returns a list that matches the condition and a list that
does not """
true_list = []
false_list = []
for item in iterable:
if condition(item):
true_list.append(item)
else:
false_list.append(item)
return true_list, false_list
a = [1, 2, 2, 3, 4, 5]
b, a = classify(a, lambda x: x > 2)
print(a) # [1, 2, 2]
print(b) # [3, 4, 5]
更新2
我没有意识到我的更新看起来与user3467349几乎相同,但不管你信不信,我没有作弊:-)