列表

3.1.4.列表lists
在python中有一些复合数据类型,通常用来使值分组在一起。最常用的是list列表,可以写成在方括号中用逗号分开的值或其他项。list可以包含不同类型的项目,但是通常大部分情况下所有的项目都是同类型的。

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

就像strings一样,在list中也可以index和slice。

>>> squares[0] # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]

所有的slice操作返回一个新的list包含其所需要的元素。这就是说下面这个slice操作返回一个新的原list的copy。

>>> squares[:]
[1, 4, 9, 16, 25]

list同样支持concatenatition操作。

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

跟string不可改变immutable的特性不同,list是可以改变内容的类型。

>>> cubes = [1, 8, 27, 65, 125] # something's wrong here
>>> 4 ** 3 # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64 # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

通过使用append()method方法,你也可以在list的结尾添加新的项目。

>>> cubes.append(216) # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

给slice赋值assignment也是可以的,这样做可能会改变list的长度,甚至全部清除了它。

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

内建函数len()可以同样应用于list。

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

list还可以嵌套nest,即在一个list中还包含另一个list。

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

 

posted @ 2015-06-21 21:09  xiaolong92  阅读(128)  评论(0)    收藏  举报