笨方法学习Python-习题34: 访问列表的元素

来源:互联网 发布:网络直播市场分析 编辑:程序博客网 时间:2024/05/22 10:26

如何获取列表元素:

列表的每一个元素都有一个地址,改地址称为“索引(index)”,索引是以“0”开头,这类数字被称为“基数”,意味着你可以抓取任意元素。


我们日常使用的计数,是从1开始的,而编程语言的计数,是从0开始的。也就是说,列表中最靠前的元素是第0号元素,而不是我们日常生活中的第1号元素。


使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示:

list1 = ['Google', 'baidu', 1997, 2000]list2 = [1, 2, 3, 4, 5, 6, 7 ] print ("list1[0]: ", list1[0])print ("list2[1:5]: ", list2[1:5])

理解基数与序数后,我们做一下练习:

animals = ['bear','python','peacock','kangaroo','whale','platypus']print("The animal at 1: %s" % animals[1])print("The 3rd animal: %s" % animals[2])print("The 1st animal: %s" % animals[0])print("The animal at 3: %s" % animals[3])print("The 5th animal: %s" % animals[4])print("The animal at 2: %s" % animals[2])print("The 6th animal: %s" % animals[5])print("The animal at 4: %s" % animals[4])