Python 有一个很好的内置列表类型,名为 “list”。List 常量写在一个中括号 [] 里面。List 和 string 的工作方式类似——使用 len() 函数和中括号 [] 来访问数据,第一个元素的索引是 0。(请见官网的 python.org list 文档)。
colors = ['red', 'blue', 'green']
print colors[0] ## red
print colors[2] ## green
print len(colors) ## 3
对于 list,用 = 赋值不会产生一份拷贝。相反,赋值会导致两个变量指向内存中同一个 list。
b = colors ## Does not copy the list
“空的 list” 只是一对空的中括号。’+’ 可以连接两个 list,所以 [1, 2] + [3, 4] 等于 [1, 2, 3, 4](这与 string + 的用法类似)。
FOR 和 IN
Python 的 for 和 in 结构非常有用,我们将在 list 上看到第一次使用它们的情况。for 结构——for var in list
——是一个很简单的查看 list(或者其它集合)中每个元素的方法。在迭代期间,不要添加或者删除 list 中的元素。
squares = [1, 4, 9, 16]
sum = 0
for num in squares:
sum += num
print sum ## 30
如果你知道 list 里面元素的类别,在循环中使用反映信息的变量名,如 “num”、”name” 或者 “url”。由于 Python 代码没有其它语法来提醒你变量的类型,因此变量名就是你了解类型的关键手段。
in 可以很容易的测试一个元素是否在一个 list(或者其它集合)里面——value in collection
——测试 value 是否在 collection 里面,然后返回 True/False。
list = ['larry', 'curly', 'moe']
if 'curly' in list:
print 'yay'
for/in 结构在 Python 代码中很经常会用到,并且除了 list 之外,在其它数据类型也适用,所以应该记住它们的用法。在其它语言中,你可能会手动地迭代一个集合,而在 Python 中只需使用 for/in。
你也可以对 string 使用 for/in。string 对于它的字符来说就像 list 对于它的元素,所以 for ch in s: print ch
会打印出 string 所有的字符。
Range
range(n) 函数产生数字 0, 1, … n-1,range(a, b) 则返回 a, a+1, … b-1——到达但不包括最后一个数字。for 循环和 range() 可以构建出一个传统的数字循环:
## print the numbers from 0 through 99
for i in range(100):
print i
有一个变体函数 xrange()。该函数在某些情况下可以避免构建整个 list 所消耗的性能(在 Python 3000,range() 已经有很好的性能了,所以可以忘掉 xrange())。
While 循环
Python 也有标准的 while 循环,break 和 continue 的工作方式与 C++ 和 Java 中的一样,在最内部的循环中改变。前面提到的 for/in 解决了迭代一个 list 中每个元素的情况,而 while 循环则让你可以完全控制索引。下面这个 while 循环每个三个元素访问 list 一次:
## Access every 3rd element in a list
i = 0
while i < len(a):
print a[i]
i = i + 3
List Methods
下面是一些常用的 list 方法:
list.append(elem) —— 将一个元素添加到列表的末尾。常见的错误:这不会返回一个新的 list,仅仅修改了原来的 list。
list.insert(index, elem) —— 在给定的索引中插入元素,将后面的元素右移。
list.extend(list2) —— 将 list2 的元素添加到 list 的末尾。对一个 list 使用 + 或者 += 相当于使用 extend()。
list.index(elem) —— 从 list 的开头查找给定元素并返回该元素的索引。如果该元素不存在,那么会抛出一个 ValueError(使用 “in” 来检查是否存在该元素,从而避免 ValueError)。
list.remove(elem) —— 查找 list 中第一个给定元素的实例并删除它(如果没有该元素,则抛出 ValueError)
list.sort() —— 将 list 进行适当的排序(不会返回新的 list)。
list.reverse() —— 适当地反转 list(不会返回新的 list)
list.pop(index) —— 删除和返回给定索引的元素。如果索引缺省,那么返回最右边的元素(大致与 append() 相反)。
注意到这些在 list 对象上的方法,与 len() 函数不同之处。len() 函数将 list(string 或者其它)作为参数。
list = ['larry', 'curly', 'moe']
list.append('shemp') ## append elem at end
list.insert(0, 'xxx') ## insert elem at index 0
list.extend(['yyy', 'zzz']) ## add list of elems at end
print list ## ['xxx', 'larry', 'curly', 'moe', 'shemp', 'yyy', 'zzz']
print list.index('curly') ## 2
list.remove('curly') ## search and remove that element
list.pop(1) ## removes and returns 'larry'
print list ## ['xxx', 'moe', 'shemp', 'yyy', 'zzz']
常见的错误:上面的方法不会返回修改过的 list,只会修改原来的 list。
list = [1, 2, 3]
print list.append(4) ## NO, does not work, append() returns None
## Correct pattern:
list.append(4)
print list ## [1, 2, 3, 4]
逐步建立 list
一个常用的模式是首先建立一个空的 list [],然后使用 append() 或者 extend() 添加元素:
list = [] ## Start as the empty list
list.append('a') ## Use append() to add elements
list.append('b')
List Slices
List 的切分与 string 上的一样,也可以用于 list 的分割。
list = ['a', 'b', 'c', 'd']
print list[1:-1] ## ['b', 'c']
list[0:2] = 'z' ## replace ['a', 'b'] with ['z']
print list ## ['z', 'c', 'd']
练习:list1.py
尝试不用排序来解决 google-python-exercises 中 list1.py 的问题(位于 basic/ 目录下)。