您的位置:首页 > 编程语言 > Python开发

Python -- Lists

2016-01-14 23:52 399 查看

Python – Lists

注:初学者,基本翻译文档而来(version:3.5.1)

Python中的Lists的书写形式如下所示:方括号之间使用逗号相隔。在Python中,Lists可以包含类型不同的条目(item,说元素或许更好熟悉),但是经常都是包含类型相同的条目。

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


和字符串一样,Lists也可以被索引(indexed)和切割(sliced)

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


切割操作返回的是一个全新的list, 即意味着下面的代码片段返回的list相当于是squares的拷贝。

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


Lists也支持串联(concatenation)操作

>>> squares + [-1, -4, -9, -16, -25]
[1, 4, 9, 16, 25, -1, -4, -9, -16, -25]


和字符串是不可变(immutable)类型不一样的是,Lists是可变(mutable)的类型

例如下面的代码段,改变list中的内容。

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


可以使用append()方法在list的末尾添加条目

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


通过切割操作,我们可以改变list的大小或者甚至完全清楚list中的items

>>> 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
[]


库函数(built-in function)len()获取list的长度

>>> letters = [1, 2, 3, 4, 5]
>>> len(letters)
5


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'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: