Problem 5: Split (50pts)
Problem
my_splittakes in a listland a functionfand splits the listlinto two separate (i.e., a pair of) lists, so that for any elementein the first returned list,f(e)evaluates toTrue; and for any elementein the second returned list,f(e)evaluates toFalse.It is guaranteed that
fis a pure functionfalways terminates andfreturns eitherTrueorFalseSuch functions are called predicates, a term from the field of logic.
my_split 接受一个列表 l 和一个函数 f,并将列表 l 分割成两个独立的列表(即一个对),
使得对于第一个返回列表中的任何元素 e,f(e) 求值为 True;
对于第二个返回列表中的任何元素 e,f(e) 求值为 False。
保证以下条件成立:
f是一个纯函数。f总是终止。f返回True或False。
这类函数被称为谓词(predicate),这是一个来自逻辑学领域的术语。
def my_split(f, l):
"""Splits the list into a pair of lists according to predicate f.
>>> my_split(lambda x: True, [1, 2, 3, 4]) # All elements from l conforms to the predicate
([1, 2, 3, 4], [])
>>> my_split(lambda x: x % 2 == 0, [1, 2, 3, 4]) # Split into even and odd numbers
([2, 4], [1, 3])
>>> my_split(lambda x: x < 5, [3, 1, 4, 1, 5, 9, 2])
([3, 1, 4, 1, 2], [5, 9])
>>> my_split(lambda x: not x, [True, False, True, True]) # There might be things other than integers
([False], [True, True, True])
>>> is_ldx = lambda x: not x.startswith('24')
>>> studentIDs = ['24122', '22122', '502024', '24183']
>>> ldx, xdx = my_split(is_ldx, studentIDs)
>>> ldx
['22122', '502024']
>>> studentIDs # You should not mutate the original list
['24122', '22122', '502024', '24183']
"""
"*** YOUR CODE HERE ***"
Hints
Hint: use list comprehensions.
- 使用列表推导式(list comprehensions)。
Solutions
def my_split(f, l):
return ([i for i in l if f(i)], [i for i in l if not f(i)])