Python手撕常用模版
标准输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| a = 10
print(a)
print("Hello" + ", " + "World!")
print("Hello", "World!", sep=", ")
s = "abc"
print(s, a)
print(f"{s} {a}")
print(f"{s} {a}", end = "")
|
标准输入(ACM模式)
- 一般读入(stdin/input)
1 2 3 4
| import sys for line in sys.stdin: a = line.split() print(int(a[0])+int(a[1]))
|
1 2 3 4 5 6 7 8 9
| while True: try: a=int(input().split(" ")[0]) b=int(input().split(" ")[-1]) print(a+b) except: break
|
- 读取多行输入且第一行为行数(即固定行数)
1 2 3 4 5
| if __name__ == '__main__': n = input() for _ in range(n) print(list(map(int, input().split())))
|
- 读取多行输入但不知有多少行(以读入空行且是空字符串结束)
1 2 3 4 5 6
| if __name__ == '__main__': arr = [] for line in iter(input,''): arr.append(line.split()) print(arr)
|
- 读取多行输入但不知有多少行(以读入空行结束)
1 2 3 4 5 6 7 8 9 10 11
| if __name__ == '__main__': try: arr = [] while True: str_input = input().strip() if str_input == '': break arr.append(str_input.split()) print(arr) except: pass
|
列表List
- 初始化
1 2 3 4 5 6 7 8 9 10 11 12 13
| nums = []
nums = [1, 3, 5]
n = 10 nums = [0] * n
m, n = 3, 4 matrix = [[1] * n for _ in range(m)]
|
- 常见方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| lst = [0] * 10
print(len(lst) == 0)
print(len(lst)) lst.append(4) lst.pop() lst.pop([index]) lst.insert(i, x) lst.extend(lst1) lst.remove(2) lst.sort() lst.reverse() lst[1] = 20
lst[-1]表示最后一个数 for i in range(0, -10, -1) for i in reversed(range(len(lst)-1))
lst = ["a", "b", "c"] for i, v in enumerate(lst): print(i, v)
date = "2019-8-15" Y, M, D = map(int, date.split('-'))
lst1=sorted(lst) lst2=sorted(lst,reverse=True) l1 = [(1,2), (0,1), (3,10)] l2 = sorted(l1, key=lambda x: x[0])
lst = [i*j for i in range(1,10)]
add = lambda a, b: a + b
x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) list(zipped)
maxnums = max(maxnums, tmp)
lst_copy = lst.copy()
import copy deep_copy = copy.deepcopy(lst)
|
多维列表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| ls = [] ls_T = list(map(list, zip(*ls))) if 元素 in ls_T[0]: j = ls_T[0].index(元素)
A = [[1,2,3],[4,5,6],[7,8,9]] print(len(A)) print(len(A[0])) B = [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))] print(B)
DIRS = [[0, 1], [1, 0], [0, -1], [-1, 0]]
di=0 nx, ny = x + DIRS[di][0], y + DIRS[di][1]
DIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)] for dx,dy in DIRS: nx,ny = x+ dx, y + dy
|
字符串String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| ord('a') chr(100)
' spacious '.strip() '1,2,3'.split(',') '1,2,3'.split(',', maxsplit=1)
str1 = '12345' list1 = list(str1) print(list1)
str3 = 'this is string example' list3 = str3.split('i', 1) print(list3)
list1 = ['1', '2', '3', '4', '5'] str1 = "".join(list1)
list3 = ['www', 'baidu', 'com'] str3 = ".".join(list3)
|
双端队列Deque
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| from collections import deque
lst = deque([1, 2, 3, 4, 5])
print(len(lst) == 0)
print(len(lst))
lst.appendleft(0) lst.append(6)
print(lst[0], lst[-1])
lst.popleft() lst.pop()
lst.insert(2, 99)
del lst[1]
for val in lst: print(val, end=" ") print()
|
队列Queue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| from collections import deque
q = deque()
q.append(10) q.append(20) q.append(30)
print(len(q) == 0)
print(len(q))
print(q[0])
q.popleft()
print(q[0])
|
栈Stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| s = []
s.append(10) s.append(20) s.append(30)
print(len(s) == 0)
print(len(s))
print(s[-1])
s.pop()
print(s[-1])
|
字典Dict
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| hashmap = {1: "one", 2: "two", 3: "three"}
print(len(hashmap) == 0)
print(len(hashmap))
if 2 in hashmap: print(f"Key 2 -> {hashmap[2]}") else: print("Key 2 not found.")
print(hashmap.get(4))
hashmap[4] = "four"
print(hashmap[4])
del hashmap[3]
if 3 in hashmap: print(f"Key 3 -> {hashmap[3]}") else: print("Key 3 not found.")
for k, v in hashmap.items(): print(f"{k} -> {v}")
|
集合Set
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| hashset = {1, 2, 3, 4}
print(len(hashset) == 0)
print(len(hashset))
if 3 in hashset: print("Element 3 found.") else: print("Element 3 not found.")
hashset.add(5)
hashset.discard(2)
if 2 in hashset: print("Element 2 found.") else: print("Element 2 not found.")
for element in hashset: print(element)
|
计数器Counter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| from collections import Counter
list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"] dic = Counter(list1) print(dic)
print(dict(dic))
print(dic.items())
print(dic.keys())
print(dic.values())
print(sorted(dic.items(), key=lambda s: (-s[1])))
for i, v in dic.items(): if v == 1: print(i)
|
经典二叉树模版
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class TreeNode: def __init__(self, val, left = None, right = None): self.val = val self.left = left self.right = right
vals=[3,9,20,None,None,15,7] def create_tree(vals, index=0): if index >= len(vals) or vals[index] is None: return None root = TreeNode(vals[index]) root.left = create_tree(vals, 2 * index + 1) root.right = create_tree(vals, 2 * index + 2) return root root = create_tree(vals)
|
由labuladong算法笔记改编而来,原链接https://labuladong.online/algo/programming-language-basic/python/