python中有很多容器用来存储数据,方便再次用到,这里介绍列表,集合和字典的常用方法。
一.列表(list)
- 列表是可变的,有序的,可重复的
1. 索引
正索引 :从左至右 0 开始
负索引 :从右至左 -1 开始
2. 列表切片
list = [1,2,3,4,5,6,7,8,9]
print(list[2:])
>>> [3, 4, 5, 6, 7, 8, 9]
print(list[2:6])
>>> [3, 4, 5, 6]
3. in
判断元素是否在列表
list = [1,2,3,4,5,6,7,8,9]
3 in list
>>> True
4. 常用方法
index (索引)
list 索引从0开始
list = [1,2,2,3,4,5,6,6,6]
list.index(2)
>>> 1
count (计数)
计算元素出现的次数
list = [1,2,2,3,4,5,6,6,6]
list.count(6) #元素出现次数
>>> 3
len (长度)
列表的长度(或元素个数)
list = [1,2,3,4,5,6]
len(list) # 列表长度
>>> 6
append (尾部追加)
list = [1,2,3,4]
list.append(6)
print(list)
>>> [1, 2,