首页 > 技术文章 > Python学习笔记 第一课 列表

ibgo 2013-12-21 23:58 原文

Python的列表就像是一个数组:

一、创建列表

movies=["The Holy Grail","Then Life of Brian","The Meaning of Life"]

这里的movies是一个变量,而且不需要声明变量的类型。

数组是从0开始计数的。如果要访问列表里的数据,可以这样:

['The Holy Grail', 'Then Life of Brian', 'The Meaning of Life']
>>> movies[1]
'Then Life of Brian'
The Holy Grail的索引是0,Then Life of Brian的索引是1,The Meaning of Life的索引是2.
整个列表中有3个数据项,用len()函数:
>>> print(len(movies))
3

可以看到答案是3。

二、操作列表

1、添加数据项

用append()方法可以在列表末尾添加一个数据项:

>>> movies.append("Titanic")
>>> print(movies)
['The Holy Grail', 'Then Life of Brian', 'The Meaning of Life', 'Titanic']

2、移除数据项

用pop()方法可以从列表的末尾移除一个数据项,让我想到了从栈中弹出。

1 ['The Holy Grail', 'Then Life of Brian', 'The Meaning of Life', 'Titanic']
2 >>> movies.pop()
3 'Titanic'

第三行显示Titanic从列表中移除了,真的吗?让我们看看现在的电影列表里还有些什么:

1 >>> movies.pop()
2 'Titanic'
3 >>> print(movies)
4 ['The Holy Grail', 'Then Life of Brian', 'The Meaning of Life']

是的,列表中只有3个数据项了,Titanic已被移除。

3、添加数据项集合

用extend()方法可以在列表末尾增加一个数据项集合,就是和另一个列表合并。

先创建另一个列表:

>>> myList=['Cleese', 'Palin', 'Jones', 'Idle']

然后用extend()方法把这个myList列表添加到movies列表的后面:

1 >>> myList=['Cleese', 'Palin', 'Jones', 'Idle']
2 >>> movies.extend(myList)
3 >>> print(movies)
4 ['The Holy Grail', 'Then Life of Brian', 'The Meaning of Life', 'Cleese', 'Palin', 'Jones', 'Idle']

可以看到myList列表已经添加到了movies列表的后面。

4、删除特定数据项

如果要删除某个数据项——注意不是从列表的末尾移除,可以用remove()方法,括号内写要删除的数据项名字。

1 >>> movies.remove("Cleese")
2 >>> print(movies)
3 ['The Holy Grail', 'Then Life of Brian', 'The Meaning of Life', 'Palin', 'Jones', 'Idle']

可以看到Cleese已经从列表中删除了。

5、在某个位置添加数据项

用insert()方法可以在列表的任意位置添加数据项。

1 >>> movies.insert(0,"Hello World")
2 >>> print(movies)
3 ['Hello World', 'The Holy Grail', 'Then Life of Brian', 'The Meaning of Life', 'Palin', 'Jones', 'Idle']

我们已经知道列表的计数是从0开始的,所以这里Hello World就被添加到了列表的开头。

练习题:

如果要得到这样的一个列表该怎么办?

["The Holy Grail", 1975, "The Life of Brian", 1979, "The Meaning of Life", 1983]

本以为刚学到的insert(),append()等方法会派上用场,而且感觉是个活学活用的好主意。可是书上的答案是第二种——直接手写出这个列表,免去了一些计算,因为这是一个小列表。

这让我想到Python的设计者开发时总的指导思想是,对于一个特定的问题,只要有一种最好的方法来解决就好了。这在由Tim Peters写的python格言(称为The Zen of Python)里面表述为:

There should be one - and preferably only one - obvious way to do it.

--End--

推荐阅读