列表
序号 |
方法 |
1 |
list.append(obj) |
2 |
list.count(obj) |
3 |
list.extend(seq) |
4 |
list.index(obj) |
5 |
list.insert(index, obj) |
6 |
list.pop([index=-1]]) |
7 |
list.remove(obj) |
8 |
list.reverse() |
9 |
|
10 |
list.clear() |
11 |
list.copy() |
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 列表操作 """ # 连接操作:+ # a = [1] # b = [2] # c = a + b #[1, 2] # print(c) # 重复 * # a = [1] # c = a * 3 # [1, 1, 1] # print(c) # 索引 # a = [1, 2, 3] # b = a[1] #2 # print(b) # 切片 # a = [1, 2, 3] # b = a[0:2] # [ 1, 2] # print(b) # len() 长度 # a = [1, 2, 3] # b = len(a) # 3 # print(b) # max() 最大值 # a = [1, 2, 3] # b = max(a) # 3 # print(b) # min() 最小值 # a = [1, 2, 3] # b = min(a) # 1 # print(b) # list() # a = list((1, 2, 3)) # [1, 2, 3] # print(a) # 增加元素append(self, p_object) # a = [1, 2, 3] # b = 4 # a.append(b) # [1, 2, 3, 4] # print(a) # 可以可迭代对象个每个元素添加到列表extend(self, iterable) # a = [1, 2, 3] # a.extend('abc') # [1, 2, 3, 'a', 'b', 'c'] # print(a) # 在指定索引增加元素insert(self, index, p_object) # a = [1, 2, 3] # a.insert(1, 5) # [1, 5, 2, 3] # print(a) # 删除元素del() # a = [1, 2, 3] # del a[1] # [1, 3] # print(a) # 删除指定索引的元素pop(self, index=None) # a = [1, 2, 3, 4] # b = a.pop() # 4 # a.pop(5)# IndexError:pop index out of range # print(a) # [1, 2, 3] # print(b) # 删除指定值元素remove(self, value) # a = [1, 2, 3, 4] # a.remove(3) # [1, 2, 4] # a.remove(5) # ValueError: list.remove(x): x not in list # print(a) # 清空所有元素clear(self) # a = [1, 2, 3] # a.clear() # [] # print(a) # 修改元素 # a = [1, 2, 3] # a[1] = 5 # [1, 5, 3] # print(a) # 查找元素 # a = [1, 2, 3] # b = 2 in a # True # b = 5 in a # False # print(b) # 查找元素在列表中第一次出现的位置 index(self, value, start=None, stop=None) # a = [1, 2, 3, 3,2, 3] # index = a.index(2) # 1 # index = a.index(2,2,5) # 4 # index = a.index(5) # ValueError: 5 is not in list # print(index) # 字符串转列表 # a = "abc" # b = list(a) # ['a', 'b', 'c'] # print(b) # 出现次数count(self, value) # a = "abcda" # b = list(a) # b = b.count("a") # 2 # print(b) # 浅复制copy(self) # a = [1, 2, 3] # b = a.copy() # [1, 2, 3] # print(b) # 列表反转reverse(self) # a = [1, 2, 3] # a.reverse() # [3, 2, 1] # print(a) # 利用切片反转列表 # a = [1, 2, 3] # b = a[::-1] # [3, 2, 1] # print(b) # 排序sort(self, key=None, reverse=False): # a = [2, 1, 3] # a.sort() # [1, 2, 3] # a.sort(reverse=True) # [3, 2, 1] # print(a)
字符串与列表相互转化
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 字符串与列表相互转换 """ # 字符串根据某个分割符转换为列表 str.split(self, sep=None, maxsplit=-1) # s = "Hello World!" # print(s.split()) # ['Hello', 'World!'] # 列表转字符串 join() # a = ['Hello', 'World!'] # b = " ".join(a) # Hello World! # print(b)