python 基础知识
2022, Nov 03
一. 简介:
https://docs.python.org/zh-cn/3.10/tutorial/appetite.html
二. 版本控制
linux: pyenv
windows: pyenv-windows
三. 数据类型
- 数字 number
int和float,Decimal或Fraction,复数,后缀 j 或 J 用于表示虚数。
当前只讨论int整型与float浮点型。
int整型 对应整数(例如:1,2,3),float浮点型 对应小数(例如:1.2,1.3)。可通过运算符+、-、*、/等 进行数学运算。混合类型的数的运算会把整数转换为浮点数。
参考文档:https://docs.python.org/zh-cn/3.10/library/stdtypes.html#numeric-types-int-float-complex - 字符串 string

字符串有多种表现形式,用单引号(’……’)或双引号(”……”)标注。(例如:’单引号包裹的字符串’,”双引号包裹的字符串”)。
当字符串中有特殊的字符时,用反斜杠\于转义。(例如:’这段字符串有英文单引号\’‘)。
字符串字面值可以包含多行。 一种实现方式是使用三重引号:”"”…””” 或 ‘'’…’’‘。print("""\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to """) # Usage: thingy [OPTIONS] # -h Display this usage message # -H hostname Hostname to connect to相邻的两个或多个 字符串字面值 (引号标注的字符)会自动合并,这项功能只能用于两个字面值,不能用于变量或表达式:
x = 'Py' 'thon' print(x) # 'Python'索引还支持负数,用负数索引时,从右边开始计数。
word = 'Python' word[0] # character in position 0 # 'P' word[5] # character in position 5 # 'o' word[-1] # last character # 'n'字符串还支持切片。索引可以提取单个字符,切片 则提取子字符串。切片索引的默认值很有用;省略开始索引时,默认值为 0,省略结束索引时,默认为到字符串的结尾。
word[0:2] # characters from position 0 (included) to 2 (excluded) # 'Py' word[2:5] # characters from position 2 (included) to 5 (excluded) # 'tho' word[:2] # character from the beginning to position 2 (excluded) # 'Py' word[4:] # characters from position 4 (included) to the end # 'on' word[-2:] # characters from the second-last (included) to the end # 'on'参考文档:https://docs.python.org/zh-cn/3.10/library/stdtypes.html#text-sequence-type-str
- 数组 list
列表是可变序列,通常用于存放同类项目的集合,支持类字符串的切片获取子数组.
参考文档:https://docs.python.org/zh-cn/3.10/library/stdtypes.html#lists - 元组 tuple
元组是不可变序列,通常用于储存异构数据的多项集。元组的其实是逗号而不是圆括号。直接通过序号修改元组内容是不被允许的。x = 1, 2, 3 y = (1, 2, 3)参考文档:https://docs.python.org/zh-cn/3.10/library/stdtypes.html#tuples
- 字典 dict
参考文档:https://docs.python.org/zh-cn/3.10/library/stdtypes.html#dictionary-view-objects - 集合 set
可用于去重
x = [1, 2, 3, 3, 4, 4, 5] x = list(set(x)) print(x) # [1, 2, 3, 4, 5]参考文档:https://docs.python.org/zh-cn/3.10/tutorial/datastructures.html#sets
- 函数 function
参考文档:https://docs.python.org/zh-cn/3.10/tutorial/controlflow.html#defining-functions