方法:
1、list.count()统计:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list_count = list.count(4) # 统计某个元素在列表中出现的次数 print("4 在列表中出现过 %s 次" % list_count) 4 在列表中出现过 2 次
2、list.append()添加对象:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.append("obj") # 在列表末尾添加新的对象,append添加元素不改变数据结构属性 print(list) [6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 'obj']
3、list.extend()扩展列表:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list1 = [123, 456, 789] list.extend(list1) # 扩展列表,在列表末尾一次性追加另一个列表中的多个值(相当于把list1的元素复制到了list) print(list) [6, 4, 5, 2, 744, 1, 76, 13, 8, 4, 123, 456, 789]
4、list.pop()删除对象:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.pop(1)#移出列表中的一个元素,(默认最后一个元素) print(list) [6, 5, 2, 744, 1, 76, 13, 8, 4]
5、list.remove()删除匹配项:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.remove(4) # 移除列表中某个值的第一个匹配项(只会移出第一个) print(list) [6, 5, 2, 744, 1, 76, 13, 8, 4]
6、list.insert()插入对象:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.insert(3, "test")#将对象插入列表的第三个位置 print(list) [6, 4, 5, 'test', 2, 744, 1, 76, 13, 8, 4]
7、list.copy复制列表:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list1 = list.copy() # 复制一个副本,原值和新复制的变量互不影响 print(list1) [4, 8, 13, 76, 1, 744, 2, 5, 4, 6]
8、list.reverse()反向排序:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.reverse() # 反向列表中元素 print(list) [4, 8, 13, 76, 1, 744, 2, 5, 4, 6]
9、list.index()获取索引:
# 修改第一个获取到对象 list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list_index = list.index(4) # 从列表中找出某个值第一个匹配项的索引位置 list[list_index] = 999 #将我们获取到的索引给他修改为999 print(list) [6, 999, 5, 2, 744, 1, 76, 13, 8, 4]
# 修改所有获取到对象 list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] for i in range(list.count(4)): # 用列表的方法count找到有多少元素等于4,然后for在来循环 list_index = list.index(4) # 找到的每一个4都用来赋给list_index list[list_index] = 999 # 最后将最后将我们获取到的索引改为999 print(list) # print我放入了for循环里面,所以输出了两条,但是从这里我们可以看到,第一次改了第一个4,第二次改了第二个4 [6, 999, 5, 2, 744, 1, 76, 13, 8, 4] [6, 999, 5, 2, 744, 1, 76, 13, 8, 999]
10、list.sort()排序:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] list.sort()#对原列表进行排序.根据ascii排序 print(list) [1, 2, 4, 4, 5, 6, 8, 13, 76, 744]
11、list[obj]步长:
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] print(list[0:-1:2]) # 这个被称为步长,最后一个2代表每隔2个元素打印一次,默认就是一步 print(list[::2]) # 这种效果和上面差不多,如果是从0开始,可以把0省略不写
函数:
12、len(list):
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] len(list) # 返回列表元素的个数 print(len(list)) 10
13、max(list):
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] print(max(list))# 返回列表元素的最大值 744
14、min(list):
list = [6, 4, 5, 2, 744, 1, 76, 13, 8, 4] print(min(list))# 返回列表元素的最小值 744