一、前 言
列表(list)是 Python 内置的可变序列,使用方式类似 JavaScript 的数组。以 CPython 为例,列表底层采用动态数组实现,而不是链表,因此可以按索引快速访问元素。
二、语 法
1、list(列表)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
team = ['封不觉', '似雨若黎', '悲灵笑骨', '枉叹之', '石上花间']
len(team)
team[0]
team[-1]
team[-2]
team.append('絮怀殇') print(team)
team.insert(1, '吞天鬼骁') print(team)
team.pop() print(team)
team.pop(5) print(team)
team.append('吞天鬼骁') print(team)
team.remove('吞天鬼骁') print(team)
team.append('吞天鬼骁') print(team) while '吞天鬼骁' in team: team.remove('吞天鬼骁') print(team)
team[0] = '疯不觉' print(team)
team[0:2]
team[-2:]
|
2、tuple(元组)
元组是不可变的有序序列,没有 append、insert 等修改方法。当一组数据在创建后不应改变时,可以用元组表达这种语义。
1 2 3 4 5
|
team = ('湿婆', '大梵天', '阿修罗', '毗湿奴') print(team[-2])
|
元组有两点需要着重说一下,元组定义是(),这个与计算公式里的()是有冲突的,所以,当我们在定义只有一个元素的元组时,尽量使用(1,)后面加个,以区分:
1 2 3 4 5 6 7 8 9 10 11
| team = (1) print(team)
team = (1,) print(team)
team = () print(team)
|
最后我们再来看下下面这个例子:
1 2 3 4
| team = ('apple', 'orange', 'banana', ['pear', 'peach']) team[3][0] = '熊' print(team)
|