本體語法
自定義輸出行爲:
方法一:
1 2import sys sys.stdout.write("Hello!\n")方法二:
1 2def printf(string : str): print(string, end='', sep='')自定義讀入行爲:
1 2 3 4 5 6 7 8 9 10 11 12 13 14>>> import sys >>> line = sys.stdin.read() Hello World! >>> # line = "Hello World!\n" >>> line = sys.stdin.readline().rstrip('\n') Hello World! >>> # line = "Hello World!" >>> char = sys.stdin.read(1) Hello World! >>> # char = 'H' >>> all_content = sys.stdin.read() >>> # read to EOF (suitable for pipe) >>> for line in sys.stdin: ... print(repr(line)) # to print '\n' explicitly cuz `line` has '\n' surfix<str>.title()以首字母大寫返回每一個單詞,<str>.upper()大寫,<str>.lower()小寫+拼接str\t製表符<str>.lstrip(), <str>.rstrip(), <str>.strip(),返回str左右兩端空格,不修改,修改另存儲爲<str> = <str>.strip()""字符串可以換行,''字符串不可換行print(a, b)的默認行爲是a,<space>b\nstr拼接需強轉<strA> + str(10086) + <strB>3 / 2 = 1, 3.0 / 2.0 = 1.5, 3.0 / 2 = 1.5, 3 / 2.0 = 1.5列表
[elementA, elementB, ...]<list>.append()尾插,<list>.insert(N)索引處插入,索引及右右移一位,<list>.del(N)刪除索引,<list>.pop()彈出隊尾,<list>.pop(N)彈出索引<list>.remove()根據值刪除元素<list>.sort()永久排序,<list>.sort(reverse=True)逆序,<list>.sorted()返回臨時排序<list>.reverse()永久翻轉<list>.len()長度for element in list:按引用訪問range(a,b,c):$[a,b)(step = c)$切片
<list>[a:b]:$[a,b)$<listA> = <listB>複製引用Shallow copy:
1 2 3 4 5 6import copy a = [1, 2, [3, 4]] b = a.copy() b = a[:] b = list(a) b = copy.copy(a)頂層元素修改不影響,修改嵌套的可變對象(比如
a[2].append(5))b也會改變Deep copy:
1 2a = [1, 2, [3, 4]] b = copy.deepcopy(a)tuple:
(elementA, elementB),不可以修改元組的元素,但是可以重新定義整個元組(修改元組變量)not > and > or, ==, !=, >/<(=)位運算:
運算 名稱 &按位與 |按位或 ~按位非 ^按位抑或 <</>>左右位移 位運算 > 比較運算 > 邏輯運算
檢查元素是否在list中:
element (not) in <list, array, tuple>,返回True / Falseif-elif-else檢查列表是否爲空:
if <list>,不爲空True,空False(It says this is Pytholic?)字典:
{key : value, key : value, ...},按key訪問<dict>[key],添加元素<dict.[new_key] = element,創建空字典dict = {},刪除元素del <dict>[key]遍歷字典:
for key, value in dict遍歷字典所有鍵:
for key in dict.keys()遍歷字典所有值:
for value in dict.values()默認值同
cpp全部放右側沒有函數重載
函數傳遞整數、浮點、字符串、元組傳遞地址但是修改時會另外創建新對象,列表、字典、集合傳遞地址,修改時會直接修改元素
禁止函數修改列表:將列表的副本傳遞給函數:
func(<list>[:])(潛copy)傳遞任意數量的實參:
1 2 3 4 5 6 7>>> def func(*args): ... print(args) ... >>> func('A') ('A',) >>> func('B', 'C', 'D') ('B', 'C', 'D')傳遞任意數量的關鍵字實參:
1 2 3 4 5>>> def func(**args): ... profile = {} ... for key, value in args: ... dict[key] = value ... return dict將函數存儲在模塊中:
1 2 3 4 5 6 7 8 9 10# ./a.py def func_1(): return # or `return None` # ./package/b.py def func_2(): return # ./package/__init__.py # ./main.py import a import package.b子目錄相對導入:
1 2 3 4 5 6 7 8 9- PROJETC - main.py - c.py - package |- a.py |- b.py # b.py import .a import ..cfrom module import functionfrom module import function as func類:
1 2 3 4 5 6 7class cls(): """description""" def __init__(a, b): self.a = a self.b = b def func(self): return繼承:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class A(): def __init__(a, b): self.a = a self.b = b def func(): print("A") return class B(): def __init__(a, b, c): super().__init__(a, b) self.c = c def func(): # super().func() is overrided super().func() print("B") return讀取文件:
1 2# hello.txt Hello World!1 2 3with open('hello.txt') as file_object: contents = file_object.read() print(contents)1Hello World!關鍵字
with在不需要訪問文件後將其關閉,也可使用open(), close()来控制儘管這是不推薦的文件訪問的路徑爲當前相對路徑
逐行讀取:
1 2 3with open('hello.txt') as file_obj: for line in file_obj: print(line)這樣會多出空行,因爲
line的結尾有換行符,寫爲:print(line.rstrip())即可(?)創建一個包含文件各行內容的列表(只能在
with內訪問文件對象,那麼在with外需要訪問的時候就需要用列表拷貝一份1 2 3 4with open('Hello.txt') as f: lines = f.readlines() for line in lines: print(line.rstrip())寫入文件:
1 2with open("Bye.txt", 'w') as f: f.write("Bye World!")讀取:
'r',寫入:'w',追加:'a'如果寫入的文件不存在,Python 將自動創建它
write()默認不寫入\n異常(神了,我
cpp都沒學異常)存儲數據(使用
json)(JavaScript Object Notation)使用
json.dump(), json.load():1 2 3 4import json numbers = [1, 0, 0, 8, 6] with open('data.json', 'w') as f: json.dump(numbers, f)1 2 3 4import json with open('data.json') as f: numbers = json.load(f) print(numbers)列表推导式:
1list[expr for var in iteratable_obj]1a = [x for x in range(5)]等价于:
1 2 3a = [] for x in range(5): a.append(x)约定:
for _ in range iteratable_object表示不关心循环变量1[0] * 3 == [0] + [0] + [0] == [0, 0, 0]列表相加表示拼接列表
因此创建一个$m\times n$的数组只需要:
1a = [[0] * n for _ in range(m)]或者这样定义:
1 2 3def matrix(m, n, val=0): return [val * n for _ in range(m)] a = matrix(3, 4, 1)判断值是否在
dict中:1 2if value in dict.values(): pass
標準庫
math
| |
还有一些常见函数直接隶属Python:
| |
random
| |
time
| |
time a programme
| |
sleep:
| |
datetime
| |
| |
同样还有:now.minute, now.second
创建时间:
| |
时间差:
| |
格式化:
| |
解析字符串:
| |
collections
deque
| |
Counter
统计元素出现次数:
| |
defaultdict
| |
普通dict访问不存在的key会报错,defaultdict可以自动创建默认值
比如计数:
| |
itertools
迭代器工具
排列:
| |
组合:
| |
笛卡儿积:
| |
其他:
| |
heapq
堆(默认小根堆)
bisect
在有序序列中二分
functools
函数工具,最常见是缓存:
| |
@cache会自动缓存函数结果
operator
操作函数:
| |
常用于排序:
| |
string
字符串常量
| |
re
正则表达式
os
操作系统
获取当前目录:
| |
查看文件:
| |
创建目录:
| |
环境变量:
| |
尽管现代 Python 更推荐用pathlib处理路径
pathlib
文件路径
| |
创建路径:
| |
遍历文件:
| |
递归查找:
| |
sys
Python 运行环境
命令行参数:
| |
标准输入:
| |
标准输出:
| |
退出程序:
| |
运行外部程序:
| |
copy
浅复制:copy.copy(),深复制:copy.deepcopy()