“笨办法”学Python 3 ——练习 34 获取列表元素

练习34 源代码

练习题:

用如下动物列表,列出来的序数或基数要求,写出你从列表中取到的动物。记住,如果我说“第1个”(1st)、“第2个”(2nd),那我就是在用序数,直接减1就可以了。如果我说“第1位”(at 1),那我就是在用基数,直接按这个数字取就行。
animals = [‘bear’, ‘python3.6’, ‘peacock’, ‘kangaroo’, ‘whale’, ‘platypus’]

1.The animal at 1. ----->python3.6
2.The third (3rd) animal. ------>peacock
3.The first (1st) animal. ------>bear
4.The animal at 3. ------>kangaroo
5.The fifth (5th) animal. ----->whale
6.The animal at 2. ------> peacock
7.The sixth (6th) animal. ----->platypus
8.The animal at 4. ------>whale

代码如下:

animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'platypus']
for i in range(6):
    print(f"The animal is at {i} and is a ", animals[i] ) #各动物的位置索引
    print(f"the sort of animal is {i+1} and is a ", animals[i]) #各动物的排序位置,即序数

输出结果

The animal is at 0 and is a  bear
the sort of animal is 1 and is a  bear
The animal is at 1 and is a  python3.6
the sort of animal is 2 and is a  python3.6
The animal is at 2 and is a  peacock
the sort of animal is 3 and is a  peacock
The animal is at 3 and is a  kangaroo
the sort of animal is 4 and is a  kangaroo
The animal is at 4 and is a  whale
the sort of animal is 5 and is a  whale
The animal is at 5 and is a  platypus
the sort of animal is 6 and is a  platypus

知识点:

1. 如何访问列表元素?
访问列表中的元素可以用到索引,Python 列表的第一个元素是从序号 0 开始,而不是从 1 开始,最后一个元素的索引是-1。
2. 什么是序数,什么是基数?
把能排序的数字叫做序数(ordinal numbers),因为它们能代表一定的顺序;
基数(cardinal number)意味着你可以随机取数,所以必须要有一个 0 元素。
记住:序数 == 排序,第一;基数 == 随机卡片,0。
序数-1就是基数。
3. 什么是索引?
索引和基数相同,从 0 开始的位置。

附加练习

1.你能解释为什么“2010年1月1日”中的2010年真的是2010年而不是2009年?(提示:你不能随机去取年份)
年份使用的是序数而不是基数,没有 0 年。
2. 多写一些列表,搞明白列表元素的索引,直到你能够准确掌握。&3.用 python 验证你的答案。
练习代码:

vegatable = 'tomato'    
list1 = ['apple',23,"pear","egg",4,vegatable,9]
print(list1[-1])
print(list1[-2])
print(list1[0])
print(list1[5])

结果

9
tomato
apple
tomato

常见问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值