>>> lst = ['jiang', 'xun', 'zhi'] # len() 列表长度 >>> len(lst) 3 >>> alst = ['gong', 'yu', 'xin'] # "+" 连接两个序列 >>> lst + alst ['jiang', 'xun', 'zhi', 'gong', 'yu', 'xin'] # "*" 重复序列元素 >>> lst * 3 ['jiang', 'xun', 'zhi', 'jiang', 'xun', 'zhi', 'jiang', 'xun', 'zhi'] # 序列是否包含该元素 >>> "jiang" in lst True # 按照元素字典顺序进行比较 >>> max(lst) 'zhi' >>> min(lst) 'jiang'
# 修改列表元素 # list.append(x) 向列表中追加元素 x >>> cities = ['harbin', 'changchun'] >>> cities[1] = 'beijing' >>> cities ['harbin', 'beijing'] >>> cities.append('shanghai') >>> cities ['harbin', 'beijing', 'shanghai']
# list.extend([L]) 向列表中追加列表 L 的元素 >>> la = [1, 2, 3] >>> lb = ['jiang', 'gong'] >>> la.extend(lb) >>> la [1, 2, 3, 'jiang', 'gong'] >>> lb ['jiang', 'gong']
# append() 和 extend() 的区别 # append() 是整建制的追加 # extend() 是个体化扩编 >>> alst = [1, 2, 3] >>> blst = [1, 2, 3] >>> clst = ["jiang", "gong"] >>> alst.append(clst) >>> alst [1, 2, 3, ['jiang', 'gong']] >>> len(alst) 4 >>> blst.extend(clst) >>> blst [1, 2, 3, 'jiang', 'gong'] >>> len(blst) 5
# list.count(x) x 元素出现次数 >>> la = [1, 2, 2, 1, 3, 1] >>> la.count(1) 3
# list.insert(i, x) 将 x 插入到索引是 i 的元素前面 >>> lst = ["gong", "xin"] >>> lst.insert(1, "yu") >>> lst ['gong', 'yu', 'xin']
# list.remove(x) 删除第一次出现的 x 元素,无返回值 >>> lst = ["python", "c++", "python", "java"] >>> lst.remove("python") >>> lst ['c++', 'python', 'java']
# list.pop([i]) 删除索引为 i 的元素,并将删除元素作为返回值。 # i 为空则删除列表最后一个 >>> lst.pop(1) 'python' >>> lst ['c++', 'java']
# list.reverse(L) 将元素顺序反转,不返回值 >>> a = [8, 3, 1, 4, 3, 0] >>> a.reverse() >>> a [0, 3, 4, 1, 3, 8] # reversed(L) 实现对列表的反向迭代 >>> b = reversed(a) >>> list(b) [8, 3, 1, 4, 3, 0] >>> b <list_reverseiterator object at 0x0000015DFC053710>
# list.sort() 对列表进行排序 >>> a.sort() >>> a [0, 1, 3, 3, 4, 8] # 从大到小排序 >>> a.sort(reverse = True) >>> a [8, 4, 3, 3, 1, 0] # 按字符串长度排序 >>> lst = ["java", "python", "c++", "basic", "pascal"] >>> lst.sort(key = len) >>> lst ['c++', 'java', 'basic', 'python', 'pascal']
|