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

来源:互联网 发布:数据库审计产品排名 编辑:程序博客网 时间:2024/05/20 05:06

列表的用处很大,但只有你能访问里边的内容时它才能发挥出作用来。你已经学会了按顺序读出列表的内容,但如果你要得到第 5 个元素该怎么办呢?你需要知道如何访问列表中的元素。访问第一个元素的方法是这样的:

animals = ['bear', 'tiger', 'penguin', 'zebra']

bear = animals[0]

你定义一个 animals 的列表,然后你用 0 来获取第一个元素?! 这是怎么回事啊?因为数学里边就是这样,所以 Python 的列表也是从 0 开始的。虽然看上去很奇怪,这样定义其实有它的好处,而且实际上设计成 0 或者 1 开头其实都可以,

最好的解释方式是将你平时使用数字的方式和程序员使用数字的方式做对比。

假设你在观看上面列表中的四种动物(['bear', 'tiger', 'penguin', 'zebra']) 的赛跑,而它们比赛的名词正好跟列表里的次序一样。这是一场很激动人心的比赛,因为这些动物没打算吃掉对方,而且比赛还真的举办起来了。结果你的朋友来晚了,他想知道谁赢了比赛,他会问你“嘿,谁是第 0 名”吗?不会的,他会问“嘿,谁是第 1 名?”

这是因为动物的次序是很重要的。没有第一个就没有第二个,没有第二个也没有第三个。第零个是不存在的,因为零的意思是什么都没有。“什么都没有”怎么赢比赛嘛,完全不合逻辑。这样的数字我们称之为“序数(ordinal number)”,因为它们表示的是事物的顺序。

而程序员不能用这种方式思考问题,因为他们可以从列表的任何一个位置取出一个元素来。对程序员来说,上述的列表更像是一叠卡片。如果他们想要 tiger,就抓它出来,如果想要zebra,也一样抓取出来。要随机地抓取列表里的内容,列表的每一个元素都应该有一个地址,或者一个 “index(索引)”,而最好的方式是使用以 0 开头的索引。相信我说的这一点吧,这种方式获取元素会更容易。这类的数字被称为“基数(cardinal number)”,它意味着你可以任意抓取元素,所以我们需要一个 0 号元素。

那么,这些知识对于你的列表操作有什么帮助呢?很简单,每次你对自己说“我要第 3 只动物”时,你需要将“序数”转换成“基数”,只要将前者减 1 就可以了。第 3 只动物的索引是 2,也就是 penguin。由于你一辈子都在跟序数打交道,所以你需要用这种方式来获得基数,只要减 1 就都搞定了。

记住: ordinal == 有序,以 1 开始;cardinal == 随机选取, 以 0 开始。

让我们练习一下。定义一个动物列表,然后跟着做后面的练习,你需要写出所指位置的动物名称。如果我用的是“1st, 2nd”等说法,那说明我用的是序数,所以你需要减去 1。如果我给你的是基数(0, 1, 2),你只要直接使用即可。

#!usr/bin/python# -*-coding:utf-8-*-animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']The animal at 1.# The 2st animal is at 1 and is a python.# The animal at 1 is the 2st animal and is a python.The 3rd animal.# The 3rd animal is at 2 and is a peacock.# The animal at 2 is the 3rd animal and is a peacock.The 1st animal.# The 1st animal is at 0 and is a bear.# The animal at 0 is the 1st animal and is a bear.The animal at 3.# The 4th animal is at 3 and is a kangaroo.# The animal at 3 is the 4th animal and is a kangaroo.The 5th animal.# The 5th animal is at 4 and is a whale.# The animal at 4 is the 5th animal and is a whale.The animal at 2.# The 3rd animal is at 2 and is a peacock.# The animal at 2 is the 3rd animal and is a peacock.The 6th animal.# The 6th animal is at 5 and is a platypus.# The animal at 5 is the 6th animal and is a platypus.The animal at 4.# The 5th animal is at 4 and is a whale.# The animal at 4 is the 5th animal and is a whale.

对于上述每一条,以这样的格式写出一个完整的句子:“The 1st animal is at 0 and is a bear.” 然后倒过来念:“The animal at 0 is the 1st animal and is a bear.”

使用 python 检查你的答案。

加分习题

上网搜索一下关于序数(ordinal number)和基数(cardinal number)的知识并阅读一下。

以你对于这些不同的数字类型的了解,解释一下为什么 “January 1, 2010” 里是 2010 而不是 2009?(提示:你不能随机挑选年份。)

再写一些列表,用一样的方式作出索引,确认自己可以在两种数字之间互相翻译。

使用 python 检查自己的答案。

原创粉丝点击