P118: Extract a slice from a list
从列表中切片。给定两个位置I和K,列表切片应包含原列表中从第I个至第K个元素之间的所有元素(包括第I个和第K元素)。列表中第一个位置计为1(Python内建的list位置索引是从0开始的)。照例测试用例:
from python99.lists.p118 import slice
def test_slice():
assert slice([1,2,3,4,5,6],-1,3) == [1,2,3]
assert slice([1,2,3,4,5,6],-1,7) == [1,2,3,4,5,6]
assert slice([1,2,3,4,5,6], 2,9) == [2,3,4,5,6]
assert slice([1,2,3,4,5,6], 2,4) == [2,3,4]
Python内建的数据类型list
已经提供了切片功能(Ninety-Nine Problems原来是为Prolog教学演示设计, Prolog中的list没有切片功能,也没有索引访问功能)。
代码实现:
# Extract a slice from a list.
# Given two indices, I and K, the slice is the list containing
# the elements between the I'th and K'th element of the original list
# (both limits included). Start counting the elements with 1.
def slice(l, i, k):
return l[max(0,i-1):min(len(l),k)]