P117: Split a list into two parts; the length of the first part is given

给定第一部份列表长度,将列表切分为两部份。照例还是先写测试用例:

from python99.lists.p117 import split def test_split(): assert split([1,2,3,4,5,6],0) == ([],[1,2,3,4,5,6]) assert split([1,2,3,4,5,6],-1) == ([], [1,2,3,4,5,6]) assert split([1,2,3,4,5,6],2) == ([1,2],[3,4,5,6]) assert split([1,2,3,4,5,6],5) == ([1,2,3,4,5],[6]) assert split([1,2,3,4,5,6],6) == ([1,2,3,4,5,6],[]) assert split([1,2,3,4,5,6],7) == ([1,2,3,4,5,6],[])

Python内建的数据类型list已经提供了切片功能(Ninety-Nine Problems原来是为Prolog教学演示设计, Prolog中的list没有切片功能,也没有索引访问功能)。

代码实现:

# Split a list into two parts; the length of the first part is given. def split(l, n): if n <0: return ([],l) if n> len(l): return (l,[]) return (l[0:n],l[n:len(l)])

results matching ""

    No results matching ""