P101: Find the last element of a list
求列表中最后一个元素。用单元测试描述为:
from python99.lists.p101 import find_last_one, find_last_one_recursive
def test_find_last_one():
input = [1,4,6,'s','no','X']
actual = find_last_one(input)
assert actual == 'X'
Python内建的list
是有序序列,其中每个元素都可以通过位置索引直接访问。且Python内建了函数len
,用读取任意有序序列的长度。先用len
读取list
的长度,将长度减去一即为末尾元素的位置索引。
位置索引是从
0
开始的。
## find the last element of a list
def find_last_one(list):
if len(list) == 0:
return None
return list[len(list)-1]
但用len
太没逼格了,要用递归!任意列表可被拆分为第一个元素和剩余列表。剩余列表还是列表,可以继续拆分为第一个元素和剩余列表...
当剩余列表为空时,拆出来的第一个元素即原列表中最后一个元素。
def find_last_one_recursive(list):
first = list[0]
remain = list[1:]
if remain == []:
return first
return find_last_one_recursive(remain)
单元测试:
def test_find_last_one_recursive():
input = [1,4,6,'s','no','X']
actual = find_last_one_recursive(input)
assert actual == 'X'