一 创建和操作列表
1、介绍
列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。
列表的数据项不需要具有相同的类型。
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。
2、常用的列表操作
1 | list.append(obj) 在列表末尾添加新的对象 |
2 | list.count(obj) 统计某个元素在列表中出现的次数 |
3 | list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
4 | list.index(obj) 从列表中找出某个值第一个匹配项的索引位置 |
5 | list.insert(index, obj) 将对象插入列表 |
6 | list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
7 | list.remove(obj) 移除列表中某个值的第一个匹配项 |
8 | list.reverse() 反向列表中元素 |
9 | list.sort([func]) 对原列表进行排序 |
10 | list.clear() 清空列表 |
11 | list.copy() 复制列表 |
3、举例
>>> list =[]
>>> list.append(1)
>>> list.count(2)
0
>>> list.extend([2,3,5,4])
>>> list
[1,2,3,5,4]
>>> list.index(5)
3
>>> list.insert(2,6)
>>> list
[1,2,6,3,5,4]
>>> list.pop(2)
6
>>> list
[1,2,3,5,4]
>>> list.remove(5)
>>> list
[1,2,3,4]
>>> list.reverse()
>>> list
[4,3,2,1]
>>> list.sort()
>>> list
[1,2,3,4]
二 创建和操作元组
1、介绍
Python 的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
2、举例
>>> list
[1,2,3,4]
>>> tuple =('a','b','c')
>>> list.insert(4,tuple)
>>> list
[1,2,3,4,('a','b','c')]
>>> list[4]
('a','b','c')
>>> list[1:4]
[2,3,4]
>>> tuple[2]
'c'
>>> tuple[1:-1]
('b',)