Python学习(三)Python数据结构
Chapter 2 Python基础
2.2 Python数据结构
数据结构(Data Structures)是结构化的变量,可以理解为变量的集合(collection)。
2.2.1 列表(List)
列表由一系列按特定顺序排列的元素组成。列表根据索引,按照0, 1, 2, . . .的顺序存储值。在Python中, 用方括号[ ] 来表示列表, 并用逗号来分隔其中的元素。
>>> list() #创建空列表
>>> [ ] #创建空列表
>>> a = [1, 2, 3, 4, 5] # 生成列表
>>> print(a) # 输出列表的内容
>>> len(a) # 获取列表的长度
>>> a[0] # 访问第一个元素的值,索引由0开始
>>> a[4] = 99 # 赋值(team assignment)
(1)List 添加
添加列表最简单的方法是通过逻辑运算符进行:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> print(a)
[1, 2, 3]
list.append()
尾部添加
>>> girls = []
>>> girls.append('Mary')
>>> print(girls)
['Mary']
list.extend()
列表追加
>>> models = ['Amy']
>>> girls.extend(models)
>>> print(girls)
['Mary','Amy']
list.insert()
指定位置添加
>>> girls.insert(1,'Cindy')
>>> print(girls)
['Mary', 'Cindy', 'Amy']
(2)List 移除
- 用
del
进行删除列表元素
words = ['cat','hello','pen','pencil','ruler']
del words[0]
print(words)
['hello', 'pen', 'pencil', 'ruler']
list.remove(x)
删除列表第一个出现值为x的项或指定成员
>>> a = [1,2,3,4,1,1,-1]
>>>a.remove(2) # 删除列表中第一个出现的值为2的项
>>>print(a)
> [1, 3, 4, 1, 1, -1]
words = ['cat','hello','pen','pencil','ruler']
words.remove('cat')
print(words)
['hello', 'pen', 'pencil', 'ruler']
- 用
list.pop
删除指定索引
words = ['cat','hello','pen','pencil','ruler']
words.pop(0)
print(words)
['hello', 'pen', 'pencil', 'ruler']
(3)List 索引及切片
- 显示特定位
>>>a = [1,2,3,4,1,1,-1]
print(a[0]) # 显示列表a的第0位的值
> 1
>>>print(a[-1]) # 显示列表a的最末位的值
> -1
- 在Python中处理列表的部分元素,称之为切片。
创建切片,可指定要使用的第一个元素和最后一个元素的索引。注意:左闭右开
将截取的结果再次存放在一个列表中并返回。
Python提供slicing切片标记,可访问子列表。
>>> a