1. 定义
列表(list)是一个有序的集合,包括0个(空列表)或多个元素;列表是用一对中括号把元素括起来(我们后面会介绍用一对圆括号表示的元组tuple、以及一对花括号表示的字典dictionary)。特别之处是,对于一个列表,并不要求其中的每个元素都是相同的数据类型。
2. 示例
接下来我们看几个例子。
>>> null_list = []
>>> print null_list
[]
>>> int_list = [1, 2, 3, 7, 8, 9]
>>> int_list
[1, 2, 3, 7, 8, 9]
>>> str_list = [first, second]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'first' is not defined
>>> first = "first line"
>>> str_list = [first, "second line"]
>>> str_list
['first line', 'second line']
>>> mix_objects = [1, "one", 2, "two", [], [3, 4, 5]]
>>> mix_objects
[1, 'one', 2, 'two', [], [3, 4, 5]]
>>>
以上示例含义不言自明。
3. 列表的一些操作
从本节开始,我们将看到Python面向对象的一些特征,即object.methods(parameters)的使用方法。
3.1 取列表的长度 len(list)
>>> a = []
>>> len(a)
0
>>>
>>> a = [1, 2, 3]
>>> len(a)
3
>>>
3.2 索引 object[index]
前面已经提到,列表是一个有序的集合。因此,和C++、Java一样,可以通过索引来取列表中指定位置的一个元素。而且,Python中,索引号也是从0开始的。
>>> a = [1, 2, 3]
>>> len(a)
3
>>> a = [1, 2, 3]
>>> a[0]
1
>>> a[2]
3
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
接下来,我们先简单运用for循环来遍历一个列表中的每个元素:
flying-bird@flyingbird:~/examples/python$ cat ./dump_list.py
#! /usr/bin/env python
def dump_list(the_list):
the_len = len(the_list)
for i in range(the_len):
print i, the_list[i]
a = [1, "one", 2, "two", [], [7, 8, 9]]
dump_list(a)
flying-bird@flyingbird:~/examples/python$ ./dump_list.py
0 1
1 one
2 2
3 two
4 []
5 [7, 8, 9]
flying-bird@flyingbird:~/examples/python$
或者另外一种遍历方法,也是通常使用的一种遍历方法:
flying-bird@flyingbird:~/examples/python$ cat ./dump_list.py
#! /usr/bin/env python
def dump_list(the_list):
index = 0
for i in the_list:
print index, i
index = index + 1
a = [1, "one", 2, "two", [], [7, 8, 9]]
dump_list(a)
flying-bird@flyingbird:~/examples/python$ ./dump_list.py
0 1
1 one
2 2
3 two
4 []
5 [7, 8, 9]
flying-bird@flyingbird:~/examples/python$
注:学习分为被动学习与主动学习。以上代码涉及到我们未介绍过的range()、for循环等用法,为此需要我们去查阅资料去了解其用法。事实上,通过主动查阅、主动学习,是效率最高的一种学习方式。python一个很好的资源: http://docs.python.org
3.3 切片slice
第一次遇到这个术语,可能会觉得很诡异。简单来讲,就是把一个有序对象(这里是列表)切成一片一片的,或按需切自己需要的那一片。在切片的时候,指定起始位置和结束位置即可。
如上所述,0是第一个元素,1是第二个元素,依此类推;另外一种标记方法是,最后一个元素是-1,倒数第二个是-2,依此类推。
如果不指明起始位置,那么就从第一个元素开始切片;类似地,如果不指明结束位置,就是切到最后一个元素。
切片slice语法是 “开始位置 : 结束位置”。
特别需要指出的是,切片出来的原始是包括开始位置,但不包括结束位置,即数学集合意义上的左闭右开。
示例:
>>> a = [1, 2, 3, 4, 5, 6]
>>> a[1:2]
[2]
>>> a[1:]
[2, 3, 4, 5, 6]
>>> a[1:-1]
[2, 3, 4, 5]
>>> a[:-1]
[1, 2, 3, 4, 5]
>>> a[3:2]
[]
>>> a[100:101]
[]
>>> a[-2:-1]
[5]
>>>
可以看到,切片出来的仍然是一个列表对象,这和前面的索引(取列表中的一个元素)是不同的。
此外,我们要了解Python的一个术语:不可变对象。先看例子:
>>> a = [1, 2, 3, 4, 5, 6]
>>> a[1:2]
[2]
>>> a
[1, 2, 3, 4, 5, 6]
>>> b = a[1:2]
>>> b
[2]
>>>
即切片出来的是另外一个list对象,而被切片的list对象是不变的,此谓list对象具有不可变性。
但是,指向一个list对象的变量是可以变化的:
>>> a = [1, 2, 3, 4, 5, 6]
>>> a = a[1:2]
>>> a
[2]
>>>
即通过给指向一个列表对象的变量,赋值一个新的list对象的时候,这个列表变量的值就改变了。——这和Java对对象的处理方式是一致的。即变量本身没有存储数据,它相当于是一个指针,指向实际的对象。——自然,这是针对对象类型来说的。对于基本数据类型,如整型等,不需要这么复杂的理解。
3.4 连接
使用加号(+)表达式,可以把两个列表的值连接起来。
>>> a = [1, 2, 3]
>>> print a + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> print a
[1, 2, 3]
>>> a = a + [4, 5, 6]
>>> a
[1, 2, 3, 4, 5, 6]
>>>
3.5 追加元素
对应append(element)方法。
加号是把两个列表的元素合并在一起,而追加元素的含义是在一个列表后面新增加一个元素。注意区分两者的含义。
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3]
>>> a.append(b)
>>> a
[1, 2, 3, [4, 5, 6]]
>>> b
[4, 5, 6]
>>> a.append(4)
>>> a
[1, 2, 3, [4, 5, 6], 4]
>>>
3.6 删除元素
删除元素有两种方法:
- list.pop(index): 删除指定索引位置的元素,索引以0开始;这个方法有返回值,返回被删除的元素;
- list.remove(element):删除指定的元素(不是索引号);和pop()的区别是该方法没有返回值;
pop()方法的例子:
>>> a=[1,2,3,4]
>>> x = a.pop(0)
>>> x
1
>>> a
[2, 3, 4]
>>> x = a.pop(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> a
[2, 3, 4]
>>> x
1
>>>
remove()方法的例子:
>>> a = [1, 2, 3, 1, 2, 3]
>>> x = a.remove(1)
>>> x
>>> a
[2, 3, 1, 2, 3]
>>> a.remove(3)
>>> a
[2, 1, 2, 3]
>>> a.remove(33)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> a = ["first", "second", "first"]
>>> a.remove('first')
>>> a
['second', 'first']
>>>
说明:最后一个例子在表示字符串的时候,用到了单引号和双引号两种,其目的仅在于复习字符串的不同表示方式,实际项目中,且不可在不同的表示方式之间来回切换。
3.7 排序
对应的方法是sort()方法,按照升序排列。
>>> a = [1,3,2,4,6,5]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5, 6]
>>> a = [1, "first", 2, "two"]
>>> a.sort()
>>> a
[1, 2, 'first', 'two']
>>> b = a.sort()
>>> a
[1, 2, 'first', 'two']
>>> b
>>> a = [1, "first", 2, "two"]
>>> a.sort(reverse=True)
>>> a
['two', 'first', 2, 1]
>>> a = [1, "first", 2, "two"]
>>> b = sorted(a)
>>> a
[1, 'first', 2, 'two']
>>> b
[1, 2, 'first', 'two']
>>>
说明几点:
- a.sort()会改变a的值;
- b = sorted(a): 保持a不变,b是a排序后的取值;
- 缺省按照升序排列,但也可以指定逆序。
3.8 反转
顾名思义,就是把列表中的元素倒过来排列。
>>> a=[1,2,3,4]
>>> b = a.reverse()
>>> a
[4, 3, 2, 1]
>>> b
>>>
3.9 赋值
>>> a=[1,2,3,4]
>>> a[0]=10
>>> a
[10, 2, 3, 4]
>>>
3.10 判断是否存在指定元素
>>> a = [1, 2, 3, 4]
>>> 5 in a
False
>>> 1 in a
True
>>>
3.11 确定元素在列表中的位置
>>> a = [1, 2, 3, 4]
>>> a.index(3)
2
>>> a.index(1)
0
>>> a.index(100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 100 is not in list
>>>
3.12 把列表转换成字符串
主要使用字符串的join方法:
>>> cur_dir = "/home/flying-bird/examples/python/"
>>> cur_dirs = cur_dir.split("/")
>>> cur_dirs
['', 'home', 'flying-bird', 'examples', 'python', '']
>>> cur_dir2 = "/".join(cur_dirs)
>>> cur_dir2
'/home/flying-bird/examples/python/'
>>>
再来一个例子,是IP地址:
>>> ip = "192.168.1.4"
>>> numbers = ip.split(".")
>>> numbers
['192', '168', '1', '4']
>>> ip_new = ".".join(numbers)
>>> ip_new
'192.168.1.4'
>>>
当然,在上面的例子中,我们也看到了字符串如何分割成列表。
4. 一些高级用法
4.1 示例1:对列表中的数值进行简单计算
>>> a = [1, 2, 3, 4]
>>> b = [i + 1 for i in a]
>>> a
[1, 2, 3, 4]
>>> b
[2, 3, 4, 5]
>>> c = [i * i for i in a]
>>> c
[1, 4, 9, 16]
>>>
4.2 示例2:计算列表中每个字符串的长度
>>> a = ["a", "ab", "abc"]
>>> lens = [len(i) for i in a]
>>> lens
[1, 2, 3]
>>>
4.3 示例3:两个列表的元素两两组合
>>> a = ['a', 'b', 'c']
>>> b = ['x', 'y', 'z']
>>> [i + j for i in a for j in b]
['ax', 'ay', 'az', 'bx', 'by', 'bz', 'cx', 'cy', 'cz']
>>>
4.4 示例4:使用自定义函数
>>> def my_add(x, y):
... return x + y
...
>>>
>>>
>>> a = [1, 2, 3]
>>> b = [100, 200, 300]
>>> [my_add(i, j) for i in a for j in b]
[101, 201, 301, 102, 202, 302, 103, 203, 303]
>>>
4.5 示例5:对元素进行过滤
>>> a = [1, 2, 3]
>>> b = [100, 200, 300]
>>> [my_add(i, j) for i in a for j in b if i % 2 != 0]
[101, 201, 301, 103, 203, 303]
>>>
>>> [my_add(i, j) for i in a for j in b if i % 2 != 0 and j == 200]
[201, 203]
>>>
5. 一些注意事项
5.1 列表复制
在复制列表时,不能用a=b这种复制方法。使用这种方法,在修改a之后,b也被修改了。和Java类似,这里的复制,实际上是让a和b指向同一个列表对象。
要让复制后,a的修改不影响b,则要把b的值赋给a,且两者指向不同的对象。为此,用下面的方法:a=b[:]。
Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> b
[1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
>>> b=a[:]
>>> b
[1, 2, 3, 4]
>>> b.append(5)
>>> b
[1, 2, 3, 4, 5]
>>> a
[1, 2, 3, 4]
>>>