P120: Remove the K'th element from a list

从列表中移除第K个元素。照例还是测试用例:

from python99.lists.p120 import remove_at def test_remove_at(): assert remove_at([1, 2, 3, 4, 5, 6], 0) == (None, [1, 2, 3, 4, 5, 6]) assert remove_at([1, 2, 3, 4, 5, 6], 2) == (2, [1, 3, 4, 5, 6]) assert remove_at([1, 2, 3, 4, 5, 6], 6) == (6, [1, 2, 3, 4, 5]) assert remove_at([1, 2, 3, 4, 5, 6], 7) == (None, [1, 2, 3, 4, 5, 6])

Python内建的数据类型list已经提供了按位置索引直接访问元素和切片功能(Ninety-Nine Problems原来是为Prolog教学演示设计,Prolog中的list没有切片功能,也没有索引访问功能)。可以直接通索引定位需被移除元素,及切片功能拆分出需被移除元素前后列表片断再拼接。

  1. 首先,以第K个元素为分界点将列表拆分为三部份:K之前的元素,K元素和K之后的元素
  2. 然后,把K之前的元素和K之后的元素拼接在一起,即为移除第K个元素后的列表

代码实现:

# Remove the K'th element from a list. def remove_at(l, k): if k <= 0: return (None, l) if k > len(l): return (None, l) return (l[k-1], l[0:k-1]+l[k:len(l)])

results matching ""

    No results matching ""