Python99 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'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值