|
(1)Python拥有大量的复合数据类型,用于把其他值组合在一起。用途最广的是列表,可以写成方括号之间的逗号分隔 值(项目iterms)的列表。列表中可能包含不同类型的项目(items),但所有的项目(items)通常具有相同的类型。
>>> squares = [1, 4, 9, 16, 25]>>> squares[1, 4, 9, 16, 25] (2)像字符串(和所有内建的序列类型)一样,列表可以使用索引和切片。
>>> squares[0] # 返回一个值(项目)1>>> squares[-1]25>>> squares[-3:] #返回一个新的列表[9, 16, 25] (3)列表同时也支持连接。
>>> squares + [36, 49, 64, 81, 100][1, 4, 9, 16, 25, 36, 49, 64, 81, 100] (4)不同于不能改变的字符串,列表是可以改变的,例如可以改变列表中的内容
>>> cubes = [1, 8, 27, 65, 125] # 这里的值有一些错误,因为这是一个立方表>>> 4 ** 3 #4的立方是64,不是6564>>> cubes[3] = 64 # 替换错误的值>>> cubes[1, 8, 27, 64, 125] 可以通过append()方法,在列表结尾处添加新值。
>>> 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] 赋值切片内容也是可行的,这可能会改变列表的大小,甚至清空列表。
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> letters['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> #替换一些值>>> letters[2:5] = ['C', 'D', 'E']>>> letters['a', 'b', 'C', 'D', 'E', 'f', 'g']>>> # 移除一些值>>> letters[2:5] = []>>> letters['a', 'b', 'f', 'g']>>> # 清空列表>>> letters[:] = []>>> letters[](5)内建函数len()也可以用来表示列表的大小。>>> letters = ['a', 'b', 'c', 'd']>>> len(letters)4(6)可以创建嵌套列表。>>> 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' |
|