Writing /share/Web/wiki/data/cache/9/96bbd709a36fdc85d5f83b640af64a43.metadata failed
语法:python3语法速查
差别
这里会显示出您选择的修订版和当前版本之间的差别。
| 两侧同时换到之前的修订记录前一修订版后一修订版 | 前一修订版 | ||
| 语法:python3语法速查 [2024/01/03 09:45] – 移除 - 外部编辑 (Unknown date) 127.0.0.1 | 语法:python3语法速查 [2024/08/06 09:23] (当前版本) – [4. string] user01 | ||
|---|---|---|---|
| 行 1: | 行 1: | ||
| + | ====== python3语法速查 ====== | ||
| + | |||
| + | |||
| + | ===== - 技巧文章 ===== | ||
| + | {{indexmenu>: | ||
| + | |||
| + | ===== - 数组 list/tuple ===== | ||
| + | |||
| + | python有可变数组和不可变数组 | ||
| + | |||
| + | ==== - 不可变数组tuple ==== | ||
| + | |||
| + | 创建: | ||
| + | |||
| + | |||
| + | |||
| + | ==== - 可变数组list ==== | ||
| + | 创建: | ||
| + | < | ||
| + | |||
| + | |||
| + | === - 数组添加元素 === | ||
| + | |||
| + | 添加一个元素到数组末尾: | ||
| + | < | ||
| + | |||
| + | |||
| + | 添加另外一个数组的所有元素到一个数组: | ||
| + | |||
| + | < | ||
| + | |||
| + | 执行效果:insert_array数组内的元素全部append到dest_array, | ||
| + | |||
| + | |||
| + | |||
| + | |||
| + | |||
| + | <code python> | ||
| + | s[i] = x | ||
| + | |||
| + | item i of s is replaced by x | ||
| + | |||
| + | s[i:j] = t | ||
| + | |||
| + | slice of s from i to j is replaced by the contents of the iterable t | ||
| + | |||
| + | del s[i:j] | ||
| + | |||
| + | same as s[i:j] = [] | ||
| + | |||
| + | s[i:j:k] = t | ||
| + | |||
| + | the elements of s[i:j:k] are replaced by those of t | ||
| + | |||
| + | (1) | ||
| + | |||
| + | del s[i:j:k] | ||
| + | |||
| + | removes the elements of s[i:j:k] from the list | ||
| + | |||
| + | s.append(x) | ||
| + | |||
| + | appends x to the end of the sequence (same as s[len(s): | ||
| + | |||
| + | s.clear() | ||
| + | |||
| + | removes all items from s (same as del s[:]) | ||
| + | |||
| + | (5) | ||
| + | |||
| + | s.copy() | ||
| + | |||
| + | creates a shallow copy of s (same as s[:]) | ||
| + | |||
| + | (5) | ||
| + | |||
| + | s.extend(t) or s += t | ||
| + | |||
| + | extends s with the contents of t (for the most part the same as s[len(s): | ||
| + | |||
| + | s *= n | ||
| + | |||
| + | updates s with its contents repeated n times | ||
| + | |||
| + | (6) | ||
| + | |||
| + | s.insert(i, x) | ||
| + | |||
| + | inserts x into s at the index given by i (same as s[i:i] = [x]) | ||
| + | |||
| + | s.pop([i]) | ||
| + | |||
| + | retrieves the item at i and also removes it from s | ||
| + | |||
| + | (2) | ||
| + | |||
| + | s.remove(x) | ||
| + | |||
| + | remove the first item from s where s[i] is equal to x | ||
| + | |||
| + | (3) | ||
| + | |||
| + | s.reverse() | ||
| + | |||
| + | reverses the items of s in place | ||
| + | |||
| + | (4) | ||
| + | |||
| + | </ | ||
| + | ==== - 数组length ==== | ||
| + | <code python> | ||
| + | tmp_array = [1, 2] | ||
| + | ret_len = len(tmp_array) | ||
| + | </ | ||
| + | ===== - dict字典 ===== | ||
| + | |||
| + | ==== - 创建dict ==== | ||
| + | |||
| + | <code python> | ||
| + | |||
| + | #### 方式1 | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | True | ||
| + | |||
| + | ### 方式2 | ||
| + | import collections | ||
| + | |||
| + | dict = collections.OrderedDict() | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | ==== - functions ==== | ||
| + | |||
| + | <code python> | ||
| + | list(d) | ||
| + | Return a list of all the keys used in the dictionary d. | ||
| + | |||
| + | len(d) | ||
| + | Return the number of items in the dictionary d. | ||
| + | |||
| + | d[key] | ||
| + | Return the item of d with key key. Raises a KeyError if key is not in the map. | ||
| + | |||
| + | d[key] = value | ||
| + | Set d[key] to value. | ||
| + | |||
| + | del d[key] | ||
| + | Remove d[key] from d. Raises a KeyError if key is not in the map. | ||
| + | |||
| + | key in d | ||
| + | Return True if d has a key key, else False. | ||
| + | |||
| + | key not in d | ||
| + | Equivalent to not key in d. | ||
| + | |||
| + | keys() | ||
| + | Return a new view of the dictionary’s keys. See the documentation of view objects. | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | ==== - 使用举例 ==== | ||
| + | |||
| + | <code python> | ||
| + | for item in a_dict.keys(): | ||
| + | print(f' | ||
| + | |||
| + | </ | ||
| + | |||
| + | ===== - string ===== | ||
| + | <code python> | ||
| + | class str(object='' | ||
| + | class str(object=b'', | ||
| + | Return a string version of object. If object is not provided, returns the empty string. | ||
| + | </ | ||
| + | |||
| + | |||
| + | ===== - 文件操作 ===== | ||
| + | |||
| + | ==== - 打开文件 ==== | ||
| + | fh = open(' | ||
| + | |||
| + | 文件打开类型, | ||
| + | |||
| + | |||
| + | === - 读文件操作 === | ||
| + | |||
| + | <code python> | ||
| + | fh = open(' | ||
| + | |||
| + | for line in fh.readlines(): | ||
| + | line = line.rstrip() # 去除最右侧换行符 | ||
| + | print(f' | ||
| + | |||
| + | fh.close() | ||
| + | </ | ||
| + | | ||
| + | === - 写文件操作 === | ||
| + | |||
| + | <code python> | ||
| + | fh = open(' | ||
| + | |||
| + | fh.write(' | ||
| + | fh.write(f' | ||
| + | |||
| + | fh.close() | ||
| + | </ | ||
| + | | ||
| + | |||
| + | ==== - 关闭文件 ==== | ||
| + | <code python> | ||
| + | fh = open(' | ||
| + | |||
| + | fh.close() | ||
| + | </ | ||
| + | ==== - 其它 ==== | ||
| + | |||
| + | === - os.path === | ||
| + | | ||
| + | <code python> | ||
| + | import os | ||
| + | |||
| + | os.path.exists(path) | ||
| + | |||
| + | os.path.isfile(path) | ||
| + | os.path.isdir(path) | ||
| + | os.path.islink(path) | ||
| + | |||
| + | os.path.dirname(path) | ||
| + | os.path.basename(path) | ||
| + | |||
| + | os.path.abspath(path) | ||
| + | os.path.isabs(path) | ||
| + | |||
| + | </ | ||
| + | |||
| + | === - os === | ||
| + | <code python> | ||
| + | import os | ||
| + | |||
| + | |||
| + | os.getenv(key, | ||
| + | os.putenv(key, | ||
| + | os.unsetenv(key) | ||
| + | |||
| + | os.chmod(path, | ||
| + | os.chown(path, | ||
| + | |||
| + | os.link(src, | ||
| + | os.symlink(src, | ||
| + | |||
| + | os.remove(path, | ||
| + | os.unlink(path, | ||
| + | os.rename(src, | ||
| + | |||
| + | os.mkdir(path, | ||
| + | os.rmdir(path, | ||
| + | |||
| + | os.listdir(path=' | ||
| + | os.chdir(path) | ||
| + | os.getcwd() | ||
| + | </ | ||
| + | ===== - base function ===== | ||
| + | |||
| + | ==== - eval() ==== | ||
| + | |||
| + | 可以用来支持一些逻辑表达式的计算: | ||
| + | |||
| + | <code python | ||
| + | # | ||
| + | |||
| + | import re | ||
| + | |||
| + | |||
| + | A = ' | ||
| + | B = ' | ||
| + | C = ' | ||
| + | |||
| + | |||
| + | s_prem = ' | ||
| + | |||
| + | # re.sub(pattern, | ||
| + | # flags=re.IGNORECASE | ||
| + | |||
| + | s_new_math = s_prem | ||
| + | s_new_math = re.sub(r' | ||
| + | s_new_math = re.sub(r' | ||
| + | s_new_math = re.sub(r' | ||
| + | |||
| + | print(f' | ||
| + | |||
| + | |||
| + | try: | ||
| + | ret = eval(s_new_math) | ||
| + | print(f' | ||
| + | except SyntaxError as e: | ||
| + | print(e) | ||
| + | |||
| + | </ | ||
| + | |||
| + | | ||
| + | ==== - getopt() ==== | ||
| + | |||
| + | C-style parser for command line options | ||
| + | |||
| + | 短argument | ||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | [' | ||
| + | >>> | ||
| + | >>> | ||
| + | [(' | ||
| + | >>> | ||
| + | [' | ||
| + | </ | ||
| + | |||
| + | 长argument | ||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | [' | ||
| + | >>> | ||
| + | ' | ||
| + | >>> | ||
| + | [(' | ||
| + | >>> | ||
| + | [' | ||
| + | </ | ||
| + | |||
| + | |||
| + | 一个比较接近实用的例子 | ||
| + | <code python> | ||
| + | import getopt, sys | ||
| + | |||
| + | def main(): | ||
| + | try: | ||
| + | opts, args = getopt.getopt(sys.argv[1: | ||
| + | except getopt.GetoptError as err: | ||
| + | # print help information and exit: | ||
| + | print(err) | ||
| + | usage() | ||
| + | sys.exit(2) | ||
| + | output = None | ||
| + | verbose = False | ||
| + | for o, a in opts: | ||
| + | if o == " | ||
| + | verbose = True | ||
| + | elif o in (" | ||
| + | usage() | ||
| + | sys.exit() | ||
| + | elif o in (" | ||
| + | output = a | ||
| + | else: | ||
| + | assert False, " | ||
| + | # ... | ||
| + | |||
| + | if __name__ == " | ||
| + | main() | ||
| + | </ | ||
| + | | ||
| + | ==== - enumerate() ==== | ||
| + | enumerate(iterable, | ||
| + | |||
| + | Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable. | ||
| + | |||
| + | <code python> | ||
| + | seasons = [' | ||
| + | list(enumerate(seasons)) | ||
| + | [(0, ' | ||
| + | list(enumerate(seasons, | ||
| + | [(1, ' | ||
| + | </ | ||
| + | |||
| + | |||
| + | ===== - function ===== | ||
| + | |||
| + | ==== - 默认参数 ==== | ||
| + | |||
| + | <code python> | ||
| + | def my_sum (a, b=1): | ||
| + | return a+b | ||
| + | |||
| + | def my_append (new_item, a_list = None): | ||
| + | if a_list == None: | ||
| + | a_list = [] | ||
| + | a_list.append(new_item) | ||
| + | return a_list | ||
| + | |||
| + | </ | ||
| + | |||
| + | 总结: | ||
| + | |||
| + | * 默认值为不可变值(比如上述例子中b=1为常数不变值)时,使用不会有问题。 | ||
| + | * 普通列表项目默认值为可变值,即为对象、list、dict等,最好默认值输入为None, 在使用的时候显示将其初始化为空对象(比如上述使用的a_list = []),这样在不同位置调用此function函数不会产生相互影响。 | ||
| + | |||
| + | ===== - 条件判断 ===== | ||
| + | ==== - if ==== | ||
| + | |||
| + | <code python> | ||
| + | if (a == b) : | ||
| + | pass | ||
| + | elif (a == c) : | ||
| + | pass | ||
| + | else: | ||
| + | pass | ||
| + | |||
| + | |||
| + | if (a == b) or (e == f) : | ||
| + | pass | ||
| + | elif (a == c) not (i == j) : | ||
| + | pass | ||
| + | elif (a == c) and (m == n) : | ||
| + | pass | ||
| + | else: | ||
| + | pass | ||
| + | |||
| + | </ | ||
| + | |||
| + | ===== - 循环 ===== | ||
| + | |||
| + | ==== - for ==== | ||
| + | |||
| + | <code python> | ||
| + | for i in range(10): | ||
| + | print(i) | ||
| + | break | ||
| + | |||
| + | for i in range(1, | ||
| + | print(i) | ||
| + | continue | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | ==== - range用法 ==== | ||
| + | |||
| + | <code python> | ||
| + | # range(stop) | ||
| + | # range(start, | ||
| + | |||
| + | >>> | ||
| + | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | ||
| + | >>> | ||
| + | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | ||
| + | >>> | ||
| + | [0, 5, 10, 15, 20, 25] | ||
| + | >>> | ||
| + | [0, 3, 6, 9] | ||
| + | >>> | ||
| + | [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] | ||
| + | >>> | ||
| + | [] | ||
| + | >>> | ||
| + | [] | ||
| + | </ | ||
| + | |||
| + | ==== - while ==== | ||
| + | |||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | ... a = a -1 | ||
| + | ... print(a) | ||
| + | ... | ||
| + | 2 | ||
| + | 1 | ||
| + | 0 | ||
| + | >>> | ||
| + | </ | ||
| + | ===== - 正则表达式 ===== | ||
| + | |||
| + | <code python> | ||
| + | import re | ||
| + | |||
| + | # 用上r'' | ||
| + | |||
| + | # 可以从中间搜索 | ||
| + | if re.search(r' | ||
| + | print(f' | ||
| + | | ||
| + | # | ||
| + | if re.match(r' | ||
| + | print(f' | ||
| + | | ||
| + | | ||
| + | # 不匹配, | ||
| + | if re.match(r' | ||
| + | print(f' | ||
| + | </ | ||
| + | |||
| + | | ||
| + | ==== - group ==== | ||
| + | |||
| + | |||
| + | <code python> | ||
| + | |||
| + | >>> | ||
| + | >>> | ||
| + | 'Isaac Newton' | ||
| + | >>> | ||
| + | ' | ||
| + | >>> | ||
| + | ' | ||
| + | >>> | ||
| + | (' | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | |||
| + | ===== - python操作json ===== | ||
| + | |||
| + | <code python> | ||
| + | import collections | ||
| + | import json | ||
| + | |||
| + | |||
| + | dict0 = collections.OrderedDict() | ||
| + | dict1 = collections.OrderedDict() | ||
| + | dict0[' | ||
| + | dict0[' | ||
| + | dict0[' | ||
| + | dict0[' | ||
| + | |||
| + | dict1[' | ||
| + | dict1[' | ||
| + | dict1[' | ||
| + | |||
| + | |||
| + | ###################################################### | ||
| + | ### conver dict to json string | ||
| + | s_djs = json.dumps(dict0, | ||
| + | print(f' | ||
| + | |||
| + | ### conver json string to dict | ||
| + | tmp_dict = json.loads(s_djs) | ||
| + | for key in tmp_dict.keys(): | ||
| + | print(key) | ||
| + | |||
| + | |||
| + | ###################################################### | ||
| + | ### dict dump to json file | ||
| + | hdl0 = open(' | ||
| + | json.dump(dict0, | ||
| + | hdl0.close() | ||
| + | |||
| + | ### load json file to dict | ||
| + | hdl1 = open(' | ||
| + | tmp_dict = json.load(hdl1) | ||
| + | hdl1.close() | ||
| + | print(f' | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | 运行结果: | ||
| + | < | ||
| + | s_djs = { | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | " | ||
| + | } | ||
| + | } | ||
| + | line0 | ||
| + | line1 | ||
| + | line2 | ||
| + | line3 | ||
| + | tmp_dict = {' | ||
| + | </ | ||
| + | ===== - 格式转换或输出 ===== | ||
| + | |||
| + | ==== - String Methods ==== | ||
| + | |||
| + | <code python> | ||
| + | |||
| + | str.lower() | ||
| + | str.upper() | ||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | ==== - 字符串格式化 ==== | ||
| + | |||
| + | === - 占位符% === | ||
| + | * https:// | ||
| + | * https:// | ||
| + | |||
| + | |||
| + | <code python> | ||
| + | name = "Li hua" | ||
| + | age = 24 | ||
| + | print(" | ||
| + | |||
| + | |||
| + | name = "Li hua" | ||
| + | age = 24 | ||
| + | print(" | ||
| + | |||
| + | |||
| + | #### | ||
| + | ' | ||
| + | ' | ||
| + | |||
| + | |||
| + | ##### 数值 | ||
| + | ' | ||
| + | ' | ||
| + | |||
| + | |||
| + | |||
| + | </ | ||
| + | |||
| + | |||
| + | === - printf样式 === | ||
| + | <code python> | ||
| + | #### printf样式, | ||
| + | print(' | ||
| + | {' | ||
| + | Python has 002 quote types. | ||
| + | </ | ||
| + | |||
| + | |||
| + | === - python3.6之后 f"" | ||
| + | 在python里面双引号和单引号功能是一样的。 | ||
| + | <code python> | ||
| + | print(f' | ||
| + | </ | ||
| + | |||
| + | ==== - print to string ==== | ||
| + | <code python> | ||
| + | import io | ||
| + | import re | ||
| + | |||
| + | output = io.StringIO() | ||
| + | output.write(' | ||
| + | print(' | ||
| + | |||
| + | # Retrieve file contents -- this will be | ||
| + | # 'First line.\nSecond line.\n' | ||
| + | contents = output.getvalue() | ||
| + | contents = re.sub(r' | ||
| + | |||
| + | # Close object and discard memory buffer -- | ||
| + | # .getvalue() will now raise an exception. | ||
| + | output.close() | ||
| + | |||
| + | print(contents) | ||
| + | </ | ||
| + | ==== - str.format() ==== | ||
| + | |||
| + | Accessing arguments by position: | ||
| + | <code python> | ||
| + | >>> | ||
| + | 'a, b, c' | ||
| + | >>> | ||
| + | 'a, b, c' | ||
| + | >>> | ||
| + | 'c, b, a' | ||
| + | >>> | ||
| + | 'c, b, a' | ||
| + | >>> | ||
| + | ' | ||
| + | |||
| + | |||
| + | |||
| + | >>> | ||
| + | |||
| + | </ | ||
| + | |||
| + | Accessing arguments by name: | ||
| + | <code python> | ||
| + | >>> | ||
| + | ' | ||
| + | >>> | ||
| + | >>> | ||
| + | ' | ||
| + | </ | ||
| + | |||
| + | | ||
| + | Accessing arguments’ items: | ||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | 'X: 3; Y: 5' | ||
| + | </ | ||
| + | | ||
| + | | ||
| + | Aligning the text and specifying a width: | ||
| + | <code python> | ||
| + | >>> | ||
| + | 'left aligned | ||
| + | >>> | ||
| + | ' | ||
| + | >>> | ||
| + | ' | ||
| + | >>> | ||
| + | ' | ||
| + | </ | ||
| + | |||
| + | |||
| + | Replacing %x and %o and converting the value to different bases: | ||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | 'int: 42; hex: 2a; oct: 52; bin: 101010' | ||
| + | >>> | ||
| + | >>> | ||
| + | 'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010' | ||
| + | </ | ||
| + | |||
| + | | ||
| + | | ||
| + | | ||
| + | | ||
| + | ==== - format数值格式转换 ==== | ||
| + | |||
| + | === - float保留2位小数 === | ||
| + | |||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | ' | ||
| + | </ | ||
| + | |||
| + | |||
| + | === - 转换为二进制数(字符串) === | ||
| + | |||
| + | # Convert an integer number to a binary string prefixed with “0b”. | ||
| + | |||
| + | <code python> | ||
| + | >>> | ||
| + | ' | ||
| + | |||
| + | # 如果不想要0b开头,可以使用format ' | ||
| + | >>> | ||
| + | (' | ||
| + | >>> | ||
| + | (' | ||
| + | </ | ||