1. sorted()
函数
Python的内置函数sorted()
是一种简单而强大的排序工具。它返回一个新的已排序列表,而不会改变原始列表。默认情况下,它按升序排序。
2. python数组的基本结构
# 增加 append A = [1, 2, 3, 4] A.append(5) # 在数组末尾追加元素 print(A) # 删除 remove pop del A = [1, 2, 3, 4, 5, 1] A.remove(1) # 用于移除列表中某个值的第一个匹配项 # print(A.remove(1)) None print(A) # pop A = [1, 2, 3, 4, 5] A.pop() print(A.pop()) # 4 print(A) # [1, 2, 3] print(A.pop(1)) # 2 print(A) # [1, 3] # del A = [1, 2, 3, 2, 4, 5] del A[3] print(A) # [1, 2, 3, 4, 5] # 插入 insert A = [1, 2, 3, 4, 5] A.insert(3, 9) print(A) # [1, 2, 3, 9, 4, 5] # 查找 A = [1, 2, 3, 4, 5] if 5 in A: print('存在') A = [5, 1, 2, 3, 4, 5] print(A.index(5)) # 查找元素第一次出现的索引 # 修改 A = [1, 2, 3, 4, 5] A[1] = 9 print(A) # [1, 9, 3, 4, 5] # 反转 A = [1, 2, 3, 4, 5] A.reverse() print(A) # [5, 4, 3, 2, 1] # 排序 A = [1, 2, 3, 4, 5, 0] # print(A.sort()) # None A.sort() # 升序 print(A) # [0, 1, 2, 3, 4, 5] A.sort(reverse=True) # 降序 print(A) # [5, 4, 3, 2, 1, 0] A2 = [1, 2, 3, 4, 5, 0] sorted(A2) # 不对原数组进行操作,开辟额外空间 print(A2) # [1, 2, 3, 4, 5, 0] print(sorted(A2)) # [0, 1, 2, 3, 4, 5] # 清空 clear A = [1, 2, 3, 4, 5] A.clear() print(A) # [] # 截取 a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(a[1:3:1]) # [2, 3] print(a[:7:2]) # [1, 3, 5, 7] print(a[::-1]) # [9, 8, 7, 6, 5, 4, 3, 2, 1] print(a[:-1]) # [1, 2, 3, 4, 5, 6, 7, 8] print(a[-1]) # 9
标签:sort,常用,函数,Python,pop,A2,print,sorted,排序 From: https://www.cnblogs.com/Jocelynn/p/17799954.html