可以从这些基本体构建所有变体:def even_list(numbers):
return [x for x in numbers if not (x & 1)]
def odd_list(numbers):
return [x for x in numbers if x & 1]
def negative_list(numbers):
return [x for x in numbers if x < 0]
def positive_list(numbers):
return [x for x in numbers if x > 0]
然后测试:>>> def test():
... numbers = list(range(-3, 4))
... print even_list(numbers)
... print odd_list(numbers)
... print positive_list(numbers)
... print negative_list(numbers)
...
>>> test()
[-2, 0, 2]
[-3, -1, 1, 3]
[1, 2, 3]
[-3, -2, -1]
稍后:所以从@Kos中偷窃,您可以这样写split_list:def split_list(myList, option):
predicate = negative_list if not option else even_list
return predicate(myList)
或:def split_list(myList, option):
predicates = [negative_list, even_list]
return predicates[option](myList)
如果for-loop在被调用函数的列表理解中,不确定它是否满足您的需要。
Also:“函数名应该小写,必要时用下划线分隔单词,以提高可读性。”