以下是一个示例代码,可以将一个数字列表分成多个子列表:
def split_list(numbers, predicate):
result = []
sublist = []
for number in numbers:
if predicate(number):
if sublist:
result.append(sublist)
sublist = []
sublist.append(number)
if sublist:
result.append(sublist)
return result
# 示例使用
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
is_even = lambda x: x % 2 == 0
result = split_list(numbers, is_even)
print(result)
输出结果:
[[1], [2, 3], [4, 5], [6, 7], [8, 9], [10]]
在上述示例代码中,我们定义了一个split_list
函数,它接受两个参数:numbers
表示数字列表,predicate
表示谓词函数。predicate
函数用于确定何时将数字列表分割为子列表。在示例中,我们使用is_even
函数作为谓词函数,以将数字列表按奇偶数分割为多个子列表。
在函数内部,我们使用一个循环遍历数字列表中的每个数字。如果该数字满足谓词函数的条件,则将之前的子列表添加到结果列表中,并创建一个新的空子列表。否则,将该数字添加到当前子列表中。最后,如果最后一个子列表不为空,则将其添加到结果列表中。
最后,我们调用split_list
函数,并输出结果。在示例中,我们使用is_even
函数作为谓词函数,将数字列表按奇偶数分割为多个子列表。