企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
数据类型是一类值,每个值都只属于一种数据类型。变量不需要地显式声明数据类型,赋值时自动声明。Python 有如下数据类型: * 数字(Numbers) * 字符串(String) * 元组(Tuple) * 列表(List) * 字典(Dictionary) * 集合(Set) ***** [TOC] ***** # 2.1 数字类型 在 Python 中,数字有四种类型。整型、浮点型、复数、布尔值。 ``` int_num = 100 # 整型 float_num = 3.14 # 浮点型 complex_num = 3.0 + 3.5j # 复数 bool_ = True # 布尔值。True(非0)、False(0)。 ``` ``` # 复数 z = a + bj # 实数部分:a。通过 z.real 获取 # 虚数部分:b。通过 z.imag 获取 # 虚数单位:j。 # a、b 均为实数。 ``` **数字类型转换** int():将浮点型或纯数字字符串或单个字母字符串('a'、'b' 等)转换为整型,只保留整数部分。 ``` >>> float_a = 3.6 >>> to_int_b = int(float_a) 3 >>> s = '1234' >>> int(s) 1234 ``` float():将整型或纯数字字符串转换为浮点型。 ``` >>> int_a = 34 >>> float(int_a) 34.0 >>> st = '343' >>> float(st) 343.0 ``` complex():将整型或浮点型或纯数字字符串转换为复数 ``` >>> int_a = 5 >>> complex(int_a) (5+0j) >>> s = '23' >>> complex(s) (23+0j) ``` complex(x, y):将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。 ``` >>> complex(3.3,3.5) (3.3+3.5j) ``` bool():将所给参数转换为布尔型 ``` >>> a = 156 >>> bool(a) True ``` **算术操作符** Python 操作符用来操作变量或常量值。 算术操作符用来进行数学运算。如下: | 操作符 | 含义 | 示例 | 运算结果 | | -- | -- | -- | -- | | \*\* | 指数运算 | 2 ** 2 | 4 | | % | 取模运算 | 11 % 3 | 2 | | // | 整除运算 | 15 // 7 | 2 | | / | 除法运算 | 12 / 5 | 2.4 | | \* | 乘法运算 | 8 * 2 | 16 | | - | 减法运算 | 2 - 1 | 1 | | + | 加法运算 | 3 + 2 | 5 | 在 IDLE 中: ``` >>> 2 ** 2 4 >>> 18 % 4 2 >>> a = 15 >>> b = 3 >>> a / b 5.0 >>> 10 // -3 -4 >>> 11 / -4 -2.75 >>> -2 / 5 -0.4 ``` **位操作符** 将数字以二进制进行运算。如下: ``` a = 60 # 二进制:0011 1100 b = 13 # 二进制:0000 1101 ``` | 操作符 | 含义 | 示例 | 运算结果 | | -- | -- | -- | -- | | & | 按位与操作符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0。 | a & b | 12。二进制:0000 1100 | | \| | 按位或操作符:只要对应的二个二进位有一个为1时,结果位就为1。 | a \| b | 61。二进制:0011 1101 | | ^ | 按位异或操作符:当两对应的二进位相异时,结果为1。 | a ^ b | 49。二进制:0011 0001 | | ~ | 按位取反操作符:对数据的每个二进制位取反,即把1变为0,把0变为1。~x类似于-(x + 1) | ~a | -61。二进制:1100 0011 | | << | 左移操作符:运算数的各二进位全部左移若干位,由"<<"右边的数指定移动的位数,高位丢弃,低位补0。 | a << 2 | 240。二进制:1111 0000 | | >> | 右移操作符:把">>"左边的运算数的各二进位全部右移若干位,">>"右边的数指定移动的位数。 | a >> 2 | 15。二进制:0000 1111 | ``` >>> a = 30 >>> ~a -31 >>> a << 2 120 >>> a >> 2 7 ``` > 参考学习:[二进制、八进制、十六进制与十进制互转](https://linjianming.com/jinzhizhuanhuan.html) **比较操作符** 对两个对象进行比较,返回布尔值。假设 a=10,b=20 | 操作符 | 含义 | 示例 | 运算结果 | | -- | -- | -- | -- | | == | 等于-比较对象是否相等 | a == b | False | | != | 不等于-比较两个对象是否不相等 | a != b | True | | > | 大于-判断左边对象是否大于右边对象 | a > b | False | | < | 小于-判断左边对象是否小于右边对象 | a < b | True | | >= | 大于等于-判断左边对象是否大于等于右边对象 | a >= b | False | | <= | 小于等于-判断左边对象是否小于等于右边对象 | a <= b | True | ``` >>> a = 10 >>> b = 20 >>> a == b False >>> a < b True >>> a >= b False >>> a <= b True ``` **赋值操作符** 假设a = 10,b = 20,c = 0: | 操作符 | 含义 | 示例 | 运算结果 | | -- | -- | -- | -- | | = | 简单的赋值操作符 | c = a + b - 将 a + b 的值赋值给 c | c = 30 | | += | 加法赋值操作符 | c += a - 等效于 c = c + a | c = 10 | | -= | 减法赋值操作符 | c -= a - 等效于 c = c - a | c = -10 | | \*= | 乘法赋值操作符 | c \*= a - 等效于 c = c * a | c = 0 | | /= | 除法赋值操作符 | c /= a - 等效于 c = c / a | c = 0.0 | | %= | 取模赋值操作符 | c %= a - 等效于 c = c % a | c = 0 | | \*\*= | 幂赋值操作符 | c \*\*= a - 等效于 c = c \*\* a | c = 0 | | //= | 取整除赋值操作符 | c //= a - 等效于 c = c // a | c = 0 | ``` >>> a = 10 >>> b = 20 >>> c = 0 >>> c = a + b >>> c 30 >>> c += a >>> c 40 >>> c **= a >>> c 10485760000000000 ``` **逻辑操作符** 假设a = 10,b = 20: | 操作符 | 逻辑表达式 | 含义 | 示例 | 运算结果 | | -- | -- | -- | -- | -- | | and | x and y | 布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 | a and b | 20 | | or | x or y | 布尔"或" - 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值。 | a or b | 10 | | not | not x | 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 | not a | False | **身份操作符** | 操作符 | 描述 | 实例 | | --- | --- | --- | | is | is 是判断两个标识符是不是引用自一个对象 | **x is y**, 类似**id(x) == id(y)**, 如果引用的是同一个对象则返回 True,否则返回 False | | is not | is not 是判断两个标识符是不是引用自不同对象 | **x is not y**, 类似**id(a) != id(b)**。如果引用的不是同一个对象则返回结果 True,否则返回 False。 | **注:** id()函数用于获取对象内存地址。 ``` >>> a = 20 >>> b = 20 >>> a is b True >>> id(a) == id(b) True ``` ``` >>> a = 2324 >>> b = 2324 >>> a is b False ``` *注:* Python 中内建了 -5 到 256 这些对象,当我们重复使用这些数字时,使用的是同一个对象。 **内置函数** abs(A):求A的绝对值 ``` >>> a = -13 >>> abs(a) 13 ``` divmod(A,B):除模操作,返回一个元组,形式为 (A/B, A%B) ``` >>> divmod(4, 3) (1, 1) ``` pow(A, B):幂操作符,返回“A的B次方” ``` >>> pow(2, 2) 4 ``` round(A):返回A的四舍五入结果 ``` >>> round(5.4) 5 ``` bin(A):将十进制A转换为用二进制表示的字符 ``` >>> bin(2) '0b10' ``` oct(A):将十进制A转换为用八进制表示的字符 ``` >>> oct(8) '0o10' ``` hex(A):将十进制A转换为用十六进制表示的字符 ``` >>> hex(16) '0x10' ``` **相关模块** `math 模块` [更详细>>>](https://docs.python.org/zh-cn/3/library/math.html) ``` # 导入 math 模块,查看包含的内容 >>> import math >>> dir(math) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] ``` ceil() ~~~ 向上取整操作 格式:math.ceil(数值) 返回值:整型 ~~~ ``` >>> import math >>> math.ceil(3.14) 4 ``` floor() ~~~ 向下取整操作 格式:math.floor(数值) 返回值:整型 ~~~ ``` >>> import math >>> math.floor(3.66) 3 ``` pow() ~~~ 计算一个数值的N次方 格式: math.pow(底数,幂) 返回值:浮点类型 注意:该操作相当于**运算但是结果为浮点型 ~~~ ``` >>> import math >>> math.pow(2,2) 4.0 ``` sqrt() ~~~ 开平方 格式:math.sqrt(数值) 返回值:浮点数 ~~~ fabs() ~~~ 对一个数值获取其绝对值操作 格式:math.fabs(数值) 返回值:浮点数 ~~~ abs() ~~~ 对一个数值获取其绝对值操作 格式:abs(数值) 返回值:可能是整数可以能浮点数 注意:abs() 他是内建函数 同时返回值根据原类型决定 ~~~ modf() ~~~ 将一个浮点数拆成整数和小数部分组成的元组 格式:math.modf(数值) 返回值:元组 (小数部分, 整数部分) ~~~ ``` >>> import math >>> math.modf(3.14159) (0.14158999999999988, 3.0) ``` copysign() ~~~ 将第二个数的正负号复制给第一个数 格式:math.copysign(值1,值2) 返回值:值1 符号是值2的正负号 ~~~ ``` >>> import math >>> math.copysign(-2,6) 2.0 ``` fsum() ~~~ 将一个序列的数值进行相加求和 格式:math.fsum(序列) 返回值:浮点数 ~~~ sum() ~~~ 将一个序列的数值进行相加求和 格式:sum(序列) 返回值:数值类型 注意:此为 Python 内建函数 ~~~ 数学常量: | 常量 | 描述 | | --- | --- | | pi | 数学常量 pi(圆周率,一般以π来表示) | | e | 数学常量 e,e即自然常数。 | ``` >>> import math >>> math.pi 3.141592653589793 >>> math.e 2.718281828459045 >>> ``` `random 模块` [更详细>>>](https://docs.python.org/zh-cn/3/library/random.html) ``` # random各种使用方法 import random # 随机生成[0.1)的浮点数 print("random():", random.random()) # 随机生成1000-9999之间的整数 print("randint(1000, 9999):", random.randint(1000, 9999)) # 随机生成0-20之间的偶数 print("randrange(0, 21, 2):", random.randrange(0, 21, 2)) # 随机生成0-20之间的浮点数 print("uniform(0, 20):", random.uniform(0, 20)) # 从序列中随机选择一个元素 list_string = ['a', 'b', 'c', 'd', 'e'] print("choice(list):", random.choice(list_string)) print("choice(string):", random.choice('abcd')) # 对列表元素随机排序 list_number = [1, 2, 3, 4, 5] random.shuffle(list_number) print("shuffle(list):", list_number) # 从指定序列中随机获取指定长度的片断,返回列表 print("sample(sequence):", random.sample('abcdefg', 2)) ``` *将上方 random 相关代码保存到 random_test.py ,然后用终端运行,查看结果。* ***** # 2.2 Sequence 类型 序列类型包括字符串(String)、元组(Tuple)、列表(List)。序列类型的元素有序排列,通过索引(下标)来访问。 **索引/切片** 索引从左向右,从0开始;也可以从右向左,从\-1开始: ![索引示例](https://box.kancloud.cn/8111ac2c3a6a9d28cedaa4a3e2182904_1280x720.JPG) ``` +---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 -6 -5 -4 -3 -2 -1 ``` ``` # 通过索引访问序列元素 str1 = 'Hello Python' print(sr1[4]) # 输出:o # 切片 str1[start:end] 取 如:str1[0:4],得到 'Hell' print(str1[0:4]) # 输出:Hell # 切片 间隔取 str1[start:end:step] 如:str1[0:4:2],得到 'Hl' 即取索引 0 和 3 所对应元素。 print(str1[0:4:2]) # 输出:Hl # 输出所有元素 print(str1[:]) # 输出:Hello Python # 逆序 print(str1[::-1]) ``` **连接/相加:** seq1 + seq2。两个序列类型一致才能相加。 ``` >>> str1 = 'Hello ' >>> str2 = 'Python' >>> str1 + str2 'Hello Python' ``` **重复/相乘:** seq1 * expr。将 seq1 重复 expr 次 ``` >>> str1 = 'Python ' >>> str1 * 3 'Python Python Python ' ``` **成员操作符** | 操作符 | 描述 | 实例 | | --- | --- | --- | | in | 如果在指定的序列中找到值返回 True,否则返回 False。 | x 在 y 序列中 , 如果 x 在 y 序列中返回 True。 | | not in | 如果在指定的序列中没有找到值返回 True,否则返回 False。 | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。 | ``` >>> str1 = 'abcdefghijklmnopqrstuvwxyz' >>> 'a' in str1 True >>> 1 not in str1 Traceback (most recent call last): File "<pyshell#65>", line 1, in <module> 1 not in str1 TypeError: 'in <string>' requires string as left operand, not int >>> '1' not in str1 True ``` *注:* 以上代码出现了一个类型错误,提示我们操作符左侧对象类型应该为字符串。 **其他操作符** 比较操作符。 ``` >>> '22' > '23' False >>> [1,2,3] > [1,2,3,4] False >>> [4,5,6] > [1,2,3] True ``` **内建函数** 序列类型间转换: str(A):将对象A转换为字符型 ``` >>> str(1) '1' >>> str([1,2,3,'ads',4.5]) "[1, 2, 3, 'ads', 4.5]" ``` tuple(A):将序列A转换为元组 ``` >>> tuple('abcdefg') ('a', 'b', 'c', 'd', 'e', 'f', 'g') >>> tuple(1) Traceback (most recent call last): File "<pyshell#129>", line 1, in <module> tuple(1) TypeError: 'int' object is not iterable ``` list(A):将序列A转换为列表 ``` >>> list('Hello Python') ['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n'] ``` len(A):求序列A长度 ``` >>> str1 = 'Hello Python' >>> len(str1) 12 ``` 其他: all(seq) :如果序列的所有元素都为True,则返回True ``` >>> str1 = 'Hello Python' >>> all(str1) True ``` any(seq) :如果序列的任一元素为True,则返回True ``` >>> str2 = 'Welcom to Python' >>> any(str2) True ``` seq.count(subseq):返回子序列subseq在序列seq中出现的次数 seq.index(subseq):返回子序列subseq在序列seq中第一次出现下标 ``` >>> str3 = 'Jack Lin is a handsome man!' >>> str3.count('a') 4 >>> str3.index('a') 1 ``` *参考Python文档:* 当在序列中循环时,用 `enumerate()` 函数可以将索引位置和其对应的值同时取出 ~~~ >>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe ~~~ 当同时在两个或更多序列中循环时,可以用 `zip()` 函数将其内元素一一匹配。 ~~~ >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print('What is your {0}? It is {1}.'.format(q, a)) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue. ~~~ ***** # 2.3 字符串 **字符串** 被标识为用引号表示的一组连续字符。Python 允许使用单引号或双引号。字符串是不可变的序列数据类型,即每次对字符串进行任何更改时,都会创建全新的字符串对象。 ``` a_str = 'Hello Python' print(a_str) # 输出整个字符串。Hello Python print(a_str[0]) # 输出字符串中第一个字符。H print(a_str[0:5]) # 输出字符串中前5个字符。Hello ``` > `a_str[i]` 表示通过索引(下标)获取整个字符串中第i个字符。字符串中,第一个字符索引为0,从左向右索引依次增1 **独特表示** 长字符串:用三引号(''' ''' 或 """ """)表示,可跨越多行、无需转义,可包含单/双引号。 原始字符串:r'' 。所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母r(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 ``` >>> print( r'\n' ) \n >>> print( R'\n' ) \n ``` **eval()** 用来执行一个字符串表达式,并返回表达式的值。语法: ``` eval(expression[, globals[, locals]]) ``` * expression -- 表达式。 * globals -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。 * locals -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。 ``` >>> str1 = '''Welcom to Python.''' >>> str1 = '''Welcom to Python. ''' >>> x = 6 >>> eval('3 * x') 18 >>> eval('3 * 9') 27 >>> eval('pow(3,2)') 9 >>> eval('3 + 3') 6 >>> n = 108 >>> eval("n + 12") 120 ``` **转义字符** 在需要在字符中使用特殊字符时,python用反斜杠(\\)转义字符,注意与原始字符串区别。如下表: | 转义字符 | 描述 | | --- | --- | | \\(在行尾时) | 续行符 | | \\\\ | 反斜杠符号 | | \\' | 单引号 | | \\" | 双引号 | | \\a | 响铃 | | \\b | 退格(Backspace) | | \\000 | 空 | | \\n | 换行 | | \\v | 纵向制表符 | | \\t | 横向制表符 | | \\r | 回车 | | \\f | 换页 | | \\oyy | 八进制数,yy代表字符,例如:\\o12代表换行 | | \\xyy | 十六进制数,yy代表字符,例如:\\x0a代表换行 | | \\other | 其它的字符以普通格式输出 | ``` >>> print('Hello\n Python') Hello Python ``` **字符串格式化操作符:%** 按指定的规则连接、替换字符串并返回新的符合要求的字符串。如: ``` >>> print("我叫 %s 今年 %d 岁!" % ('小明', 10)) 我叫 小明 今年 10 岁! ``` Python字符串格式化符号: |     符   号 | 描述 | | --- | --- | |%c |  格式化字符及其ASCII码 | |%s |  格式化字符串 | |%d |  格式化整数 | |%u |  格式化无符号整型 | |%o |  格式化无符号八进制数 | |%x |  格式化无符号十六进制数 | |%X |  格式化无符号十六进制数(大写) | |%f |  格式化浮点数字,可指定小数点后的精度 | |%F |  与%f相似,但会将 `nan` 转为 `NAN` 并将 `inf` 转为 `INF`。 | |%e |  用科学计数法格式化浮点数 | |%E |  作用同%e,用科学计数法格式化浮点数 | |%g |  %f和%e的简写 | |%G |  %F和%E的简写 | [更多 >>>](https://docs.python.org/zh-cn/3/library/string.html#format-specification-mini-language) ``` >>> charA = 65 >>> print('ASCII码65代表:%c' % charA) ASCII码65代表:A ``` 辅助格式化符号: | 符号 | 功能 | | --- | --- | | \* | 定义宽度或者小数点精度 | | \- | 用做左对齐 | | + | 在正数前面显示加号( + ) | |\<sp\>| 在正数前面显示空格 | | # | 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X') | | 0 | 显示的数字前面填充'0'而不是默认的空格 | | % | '%%'输出一个单一的'%' | | (var) | 映射变量(字典参数) | | m.n | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) | ``` >>> '%2d' % 3 ' 3' >>> '%#x' % 17 '0x11' >>> '%3.3f' % 3 '3.000' >>> '%3.1f' % 3 '3.0' >>> '%5.1f' % 3 ' 3.0' >>> '% d' % 4 ' 4' ``` **格式化字符串** `str.format()` 格式化字符串的函数str.format(),增强了字符串格式化的功能。 基本语法是通过{}和:来代替%。 format 函数可以接受不限个参数,位置可以不按顺序。 | 数字 | 格式 | 输出 | 描述 | | --- | --- | --- | --- | | 3.1415926 | {:.2f} | 3.14 | 保留小数点后两位 | | 3.1415926 | {:+.2f} | +3.14 | 带符号保留小数点后两位 | | \-1 | {:+.2f} | \-1.00 | 带符号保留小数点后两位 | | 2.71828 | {:.0f} | 3 | 不带小数 | | 5 | {:0>2d} | 05 | 数字补零 (填充左边, 宽度为2) | | 5 | {:x<4d} | 5xxx | 数字补x (填充右边, 宽度为4) | | 10 | {:x<4d} | 10xx | 数字补x (填充右边, 宽度为4) | | 1000000 | {:,} | 1,000,000 | 以逗号分隔的数字格式 | | 0.25 | {:.2%} | 25.00% | 百分比格式 | | 1000000000 | {:.2e} | 1.00e+09 | 指数记法 | | 13 | {:10d} |13| 右对齐 (默认, 宽度为10) | | 13 | {:<10d} |13| 左对齐 (宽度为10) | | 13 | {:^10d} |13 | 中间对齐 (宽度为10) | | 11 |{:b} | 1011 | 二进制| ``` >>> '{:.2f}'.format(3.1415926) '3.14' >>> '{:+.2f}'.format(3.1415926) '+3.14' >>> '{:+.2f}'.format(-1) '-1.00' >>> '{:.0f}'.format(2.71828) '3' >>> '{:0>2d}'.format(5) '05' >>> '{:x<4d}'.format(5) '5xxx' >>> '{:x<4d}'.format(10) '10xx' >>> '{:,}'.format(1000000) '1,000,000' >>> '{:.2%}'.format(0.25) '25.00%' >>> '{:.2e}'.format(1000000000) '1.00e+09' >>> '{:10d}'.format(13) ' 13' >>> '{:<10d}'.format(13) '13 ' >>> '{:>10d}'.format(13) ' 13' >>> '{:^10d}'.format(13) ' 13 ' >>> '{:b}'.format(11) '1011' >>> '{:d}'.format(11) '11' >>> '{:o}'.format(11) '13' >>> '{:x}'.format(11) 'b' >>> '{:#x}'.format(11) '0xb' >>> '{:#X}'.format(11) '0XB' ``` `^`,`<`,`>`分别是居中、左对齐、右对齐,后面带宽度,`:`号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。 `+`表示在正数前显示+,负数前显示\-;` `(空格)表示在正数前加空格 b、d、o、x 分别是二进制、十进制、八进制、十六进制。 按顺序替换字符: ``` foo = 1 bar = 'bar' baz = 3.14 print('{}, {} and {}'.format(foo, bar, baz)) # Out: "1, bar and 3.14" ``` 按参数索引替换字符: ``` print('{0}, {1}, {2}, and {1}'.format(foo, bar, baz)) # Out: "1, bar, 3.14, and bar" print('{0}, {1}, {2}, and {3}'.format(foo, bar, baz)) # Out: index out of range error ``` 按参数名替换字符: ``` print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3)) # Out: "X value is: 2. Y value is: 3." ``` 使用对象属性: ``` class AssignValue(object): def __init__(self, value): self.value = value my_value = AssignValue(6) print('My value is: {0.value}'.format(my_value)) # "0" is optional # Out: "My value is: 6" ``` 使用字典键: ``` my_dict = {'key': 6, 'other_key': 7} print("My other key is: {0[other_key]}".format(my_dict)) # "0" is optional # Out: "My other key is: 7" ``` 列表、元组索引: ``` my_list = ['zero', 'one', 'two'] print("2nd element is: {0[2]}".format(my_list)) # "0" is optional # Out: "2nd element is: two" ``` **内建函数** * 适用标准序列类型的所有操作 * 常用操作 * 大小写 * 合并/拼接 * 空白 * 更改显示 * 宽度 * 编码 * 检查/查找 * 修改内容 常用操作: ``` str1 = 'Python is powerful and beautiful.' ``` —每个单词首字母大写:`str1.title() ` ``` >>> str1.title() Python Is Powerful And Beautiful.' ``` —全部大写/小写:`str.upper()` / `str.lower()` ``` >>> str1.upper() 'PYTHON IS POWERFUL AND BEAUTIFUL.' >>> str1.lower() 'python is powerful and beautiful.' ``` —首字母大写,其余小写:`str.capitalize()` ``` >>> 'it\'s a beautiful rabbit.'.capitalize() "It's a beautiful rabbit." ``` —反转大小写:`str.swapcase()` ``` >>> 'it\'s a beautiful rabbit.'.swapcase() "IT'S A BEAUTIFUL RABBIT." ``` —合并/拼接:`+` `%` `join(iterable)` ``` >>> str_a = 'Hello ' >>> str_b = 'Python' >>> str_a + str_b 'Hello Python' >>> s = '-' >>> seq = ['h','e','l','l','o',' ','p','y','t','h','o','n'] >>> s.join(seq) 'h-e-l-l-o- -p-y-t-h-o-n' ``` —空白:添加空白: `\t` `\n` 删除空白:两端 `str.strip()` 开头 `str.lstrip()` 末尾 `str.rstrip()` ``` >>> print('Hello\tPython') Hello Python >>> print('Hello\nPython') Hello Python >>> st = ' It is a nice idea. ' >>> st.strip() 'It is a nice idea.' >>> st.lstrip() 'It is a nice idea. ' >>> st.rstrip() ' It is a nice idea.' ``` 更改显示: —宽度: * str.center(width) 居中对齐,用空格填充 * str.ljust(width)/str.rjust(width) 左右对齐,用空格填充 * str.zfill(width) 用0填充 ``` >>> str_s = 'python' >>> str_s.center(12) ' python ' >>> str_s.ljust(12) 'python ' >>> str_s.rjust(12) ' python' >>> str_s.zfill(12) '000000python' ``` —编码: encode() 方法以指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。 encode()方法语法: ``` str.encode(encoding='utf-8',errors='strict') ``` 参数: * encoding -- 要使用的编码,如: UTF-8。 * errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register\_error() 注册的任何值。 返回值: 该方法返回编码后的字符串,它是一个 bytes 对象。 *---人为分割---* decode() 方法以指定的编码格式解码 bytes 对象。默认编码为 'utf-8'。 decode()方法语法: ``` bytes.decode(encoding="utf-8", errors="strict") ``` 参数: * encoding -- 要使用的编码,如"UTF-8"。 * errors -- 设置不同错误的处理方案。默认为 'strict',意为编码错误引起一个UnicodeError。 其他可能得值有 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' 以及通过 codecs.register\_error() 注册的任何值。 返回值: 该方法返回解码后的字符串。 ``` str = "随心而码" str_utf8 = str.encode("UTF-8") str_gbk = str.encode("GBK") print(str) print("UTF-8 编码:", str_utf8) print("GBK 编码:", str_gbk) print("UTF-8 解码:", str_utf8.decode('UTF-8','strict')) print("GBK 解码:", str_gbk.decode('GBK','strict')) ``` 输出: ``` 随心而码 UTF-8 编码: b'\xe9\x9a\x8f\xe5\xbf\x83\xe8\x80\x8c\xe7\xa0\x81' GBK 编码: b'\xcb\xe6\xd0\xc4\xb6\xf8\xc2\xeb' UTF-8 解码: 随心而码 GBK 解码: 随心而码 ``` 检查/查找: —count(str,beg=0,end=len(string)):返回str在string里面出现次数,可用开始索引(beg)和结束索引(end)指定搜索范围 ``` >>> m_str = 'hello python.hello good man.hello py.' >>> s_str = 'hel' >>> m_str.count(s_str) 3 ``` —find(str,beg=0,end=len(string)):检测str是否包含在string中,可用开始索引(beg)和结束索引(end)指定搜索范围,找到返回索引,否则返回-1 —rfind(str,beg=0,end=len(string)):从右向左,检测str是否包含在string中,可用开始索引(beg)和结束索引(end)指定搜索范围 ,找到返回索引,否则返回-1 ``` >>> m_str = 'hello python.hello good man.hello py.' >>> s_str = 'goo' >>> m_str.find(s_str) 19 >>> m_str.rfind(s_str) 19 ``` —index(str,beg=0,end=len(string)):跟find()类似,但是如果str不在string中,则报异常 ``` >>> m_str = 'hello python.hello good man.hello py.' >>> s_str = 'py' >>> m_str.index(s_str) 6 >>> ss_str = 'z' >>> m_str.index(ss_str) Traceback (most recent call last): File "<pyshell#41>", line 1, in <module> m_str.index(ss_str) ValueError: substring not found ``` —endswith(obj,beg=0,end=len(string)):检查字符串是否以 obj 结束,是则返回True,否则返回False,可用开始索引(beg)和结束索引(end)指定搜索范围 ``` >>> str1 = 'It is a good idea.' >>> str1.endswith('.') True ``` —startswith(obj,beg=0,end=len(string)):检查字符串是否以 obj 开头,是则返回True,否则返回False,可用开始索引(beg)和结束索引(end)指定搜索范围 ``` >>> str1 = 'It is a good idea.' >>> str1.startswith('It') True ``` —isalnum():如果字符串非空并且所有字符都是字母或数字,则返回True,否则返回False ``` >>> str1 = 'abcdefg' >>> str1.isalnum() True >>> str2 = 'abcdef3456' >>> str2.isalnum() True >>> str3 = '2345678' >>> str3.isalnum() True >>> str4 = 'sdf@234' >>> str4.isalnum() False ``` —isalpha():如果字符串非空并且所有字符都是字母,则返回True,否则返回False ``` >>> 'abcdefghijk'.isalpha() True >>> '1234chg'.isalpha() False >>> ''.isalpha() False ``` —isdigit():字符串为纯数字字符,则返回True,否则返回False ``` >>> 'a'.isdigit() False >>> '234'.isdigit() True >>> '\t'.isdigit() False >>> r'\t'.isdigit() False >>> '\n'.isdigit() False >>> 'abcde'.isdigit() False ``` —islower():如果字符串中的字符都是小写,则返回True,否则返回False ``` >>> '12314'.islower() False >>> 'abcdefg'.islower() True >>> 'Abcdef'.islower() False >>> 'ASDFGH'.islower() False >>> '%@#$%'.islower() False ``` —isspace():如果字符串是空格,则返回True,否则返回False ``` >>> ''.isspace() False >>> ' '.isspace() True >>> ' '.isspace() True ``` —istitle():如果字符串中所有的单词拼写首字母为大写,且其他字母为小写,则返回 True,否则返回 False ``` >>> str_0 = 'This Is A Title.' >>> str_0.istitle() True >>> str_1 = 'This is A Title.' >>> str_1.istitle() False >>> str_2 = 'this is a title.' >>> str_2.istitle() False ``` —isupper():如果字符串中的字符都是大写,则返回True,否则返回False ``` >>> str_case = 'IT IS A TITLE.' >>> str_case.isupper() True >>> str_case_1 = 'iT IS A TITLE.' >>> str_case_1.isupper() False >>> str_case_2 = 'it is a title.' >>> str_case_2.isupper() False ``` 修改内容: —expandtabs(tabsize=8):把字符串中的 tab 符号('\\t')转为空格,tab 符号('\\t')默认的空格数是 8。该方法返回字符串中的 tab 符号('\\t')转为空格后生成的新字符串 ``` >>> str_ = 'I am so\thandsome!' >>> print(str_.expandtabs()) I am so handsome! >>> print(str_.expandtabs(16)) I am so handsome! ``` —replace(old,new,max):返回字符串中的 old(旧字符串) 替换成 new(新字符串)后生成的新字符串,如果指定第三个参数max,则替换不超过 max 次。 ``` >>> str_ = 'hello world!' >>> old = 'hello' >>> new = 'hi' >>> str_.replace(old,new) 'hi world!' ``` —split(str="", num=string.count(str))rsplit():split()通过指定分隔符 str 对字符串进行切片,如果参数 num 有指定值,则仅分隔 num+1 个子字符串,返回分割后的字符串列表 * str -- 分隔符,默认为所有的空字符,包括空格、换行(\\n)、制表符(\\t)等。 * num -- 分割次数。默认为 -1, 即分隔所有。 ``` >>> str_sp = 'this is a beautiful place.' >>> str_sp.split(' ') ['this', 'is', 'a', 'beautiful', 'place.'] >>> str_sp.split('i',3) ['th', 's ', 's a beaut', 'ful place.'] >>> str_sp.split('t',1) ['', 'his is a beautiful place.'] ``` —rsplit():与 split() 类似,但 rsplit() 从右边开始分割 ``` >>> 'this is a beautiful girl.'.rsplit('i',1) ['this is a beautiful g', 'rl.'] ``` —splitlines([keepends]):按照行('\\r', '\\r\\n', \\n')分隔,返回一个包含各行作为元素的列表。如果参数 keepends 为 False(默认),不包含换行符;如果为 True,则保留换行符 ``` >>> 'this\n is\n\r a beaut\riful girl.'.splitlines() ['this', ' is', '', ' a beaut', 'iful girl.'] >>> 'this\n is\t\r a beaut\riful girl.'.splitlines(True) ['this\n', ' is\t\r', ' a beaut\r', 'iful girl.'] ``` —partition(str)/rpartition(str):根据 str 分割字符串为三元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。rpartition(str) 表示从右边开始分割 ``` >>> 'www.linjianming.com'.partition('.') ('www', '.', 'linjianming.com') >>> 'www.linjianming.com'.rpartition('.') ('www.linjianming', '.', 'com') ``` **** # 2.4 元组 **元组** 是一种特殊的Sequence类型,用圆括号表示,不同元素之间用逗号隔开。元组的大小和其中的元素在初始化后*不可更改*。开发者定义了一个值的常量集,并且只需不断连续读取常量集,元组将发挥巨大作用。 ``` >>> tupl = () >>> type(tupl) <class 'tuple'> >>> # 元组中只有一个元素时,应以逗号结尾 >>> tupl_1 = (12,) >>> tupl_1 (12,) >>> tupl_2 = (12,'23',124) >>> tupl_2 (12, '23', 124) ``` **访问元组元素** 通过下标索引访问 ``` >>> tup = (12,34,56,65) >>> tup[0] 12 >>> tup[-1] 65 >>> tup[-2:] (56, 65) ``` **修改元组元素将报错** ``` >>> tup = (12,34,67,99,88,33,25) >>> tup[1] = 43 Traceback (most recent call last): File "<pyshell#73>", line 1, in <module> tup[1] = 43 TypeError: 'tuple' object does not support item assignment ``` **可删除整个元组** `del tuple` ``` >>> tup = ('12','hi',12) >>> tup ('12', 'hi', 12) >>> del tup >>> tup Traceback (most recent call last): File "<pyshell#77>", line 1, in <module> tup NameError: name 'tup' is not defined ``` 删除元组后再访问元组,报错提示元组未定义。 **适用于元组的操作符** | Python 表达式 | 结果 | 描述 | | --- | --- | --- | | len((1, 2, 3)) | 3 | 计算元素个数 | | (1, 2, 3) + (4, 5, 6) | (1, 2, 3, 4, 5, 6) | 连接 | | ('Hi!',) \* 4 | ('Hi!', 'Hi!', 'Hi!', 'Hi!') | 复制 | | 3 in (1, 2, 3) | True | 元素是否存在 | | for x in (1, 2, 3): print (x,) | 1 2 3 | 迭代 | **内置函数** len(tuple) 计算元组元素个数。 ``` >>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 ``` max(tuple) 返回元组中元素最大值。 ``` >>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' ``` min(tuple) 返回元组中元素最小值。 ``` >>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' ``` tuple(seq) 将列表或字符串转换为元组。 ``` >>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu') ``` **** # 2.5 列表 **列表** Sequence类型之一,用中括号“[ ]” 表示,不同元素之间用逗号隔开。 *适用Sequence序列所有操作* ``` >>> # 定义 >>> lst = [] >>> lst [] >>> lst_1 = [12, 34, 'err'] >>> lst_1 [12, 34, 'err'] >>> # 索引与切片 >>> lst_2 = [12, 55, 'not', 'found', 404] >>> lst_2[4] 404 >>> lst_2[1:3] [55, 'not'] >>> lst_2[:-2] [12, 55, 'not'] >>> # 修改列表元素 >>> lst_3 = ['it', 'is', 'so', 'good'] >>> lst_3[3] = 'cool' >>> lst_3 ['it', 'is', 'so', 'cool'] >>> # 获取列表长度 >>> len(lst_3) 4 >>> # 删除列表元素 >>> lst_4 = [12, 34, 56, 78, 89, 120] >>> del lst_4[3] >>> lst_4 [12, 34, 56, 89, 120] >>> # 拼接 >>> lst_3 + lst_4 ['it', 'is', 'so', 'cool', 12, 34, 56, 89, 120] >>> # 重复 >>> lst_4 * 2 [12, 34, 56, 89, 120, 12, 34, 56, 89, 120] ``` **嵌套列表** ``` >>> lst_0 = [12, 34, 55, 66, 88] >>> lst_1 = [99, 111, 133] >>> lst = [lst_0, lst_1] >>> lst [[12, 34, 55, 66, 88], [99, 111, 133]] >>> lst[0] [12, 34, 55, 66, 88] >>> lst[0][1] 34 ``` **内置函数** —append(obj):在列表末尾添加一个对象(元素) ``` >>> lst = ['你好', 'Python'] >>> lst.append('难学') >>> lst ['你好', 'Python', '难学'] ``` —insert(index,obj):把对象插入到index指定位置 ``` >>> lst = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst.insert(1, 66) >>> lst [1, 66, 2, 3, 4, 5, 6, 7, 8, 9] ``` —extend(seq):把序列seq的内容添加到列表中 ``` >>> lst = [11, 22, 33] >>> str_ = 'it is so cool' >>> lst.extend(str_) >>> lst [11, 22, 33, 'i', 't', ' ', 'i', 's', ' ', 's', 'o', ' ', 'c', 'o', 'o', 'l'] >>> tup = (77, 66, 55, 44, 33) >>> lst.extend(tup) >>> lst [11, 22, 33, 'i', 't', ' ', 'i', 's', ' ', 's', 'o', ' ', 'c', 'o', 'o', 'l', 77, 66, 55, 44, 33] ``` —del:删除列表元素 ``` >>> lst = ['我', '爱', '她'] >>> del lst[1] >>> lst ['我', '她'] >>> del lst >>> lst Traceback (most recent call last): File "<pyshell#128>", line 1, in <module> lst NameError: name 'lst' is not defined ``` —pop(index=-1):读取并删除index(默认 -1,即末尾元素)位置的元素 ``` >>> lst = [22, 33, 44, 55, 66, 77, 88, 99, 111, 222, 333] >>> lst.pop() 333 >>> lst [22, 33, 44, 55, 66, 77, 88, 99, 111, 222] >>> lst.pop(4) 66 >>> lst [22, 33, 44, 55, 77, 88, 99, 111, 222] >>> lst.pop(-3) 99 >>> lst [22, 33, 44, 55, 77, 88, 111, 222] ``` —remove(obj):删除指定元素值obj。只删除第一个匹配的obj ``` >>> lst = [22, 33, 44, 55, 77, 33, 88, 11, 22] >>> lst.remove(22) >>> lst [33, 44, 55, 77, 33, 88, 11, 22] ``` —clear():清空列表 ``` >>> lst = ['我', '爱', '她'] >>> lst.clear() >>> lst [] ``` —sort( key=None, reverse=False):对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。没有返回值,但是会对列表的对象进行排序 * key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。 * reverse -- 排序规则,reverse = True降序,reverse = False升序(默认)。 ``` >>> lst = [1, 13, 24, 5, 10, 66, 35, 88, 2] >>> lst.sort() >>> lst [1, 2, 5, 10, 13, 24, 35, 66, 88] >>> lst.sort(reverse=True) >>> lst [88, 66, 35, 24, 13, 10, 5, 2, 1] ``` ``` # 获取列表的第二个元素 def takeSecond(elem): return elem[1] # 列表 random = [(2, 2), (3, 4), (4, 1), (1, 3)] # 指定第二个元素排序 random.sort(key=takeSecond) # 输出类别 print ('排序列表:', random) # Out:排序列表:[(4, 1), (2, 2), (1, 3), (3, 4)] ``` —sorted()函数对所有可迭代的对象进行排序操作。 > **sort 与 sorted 区别:** > > sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。 > > list 的 sort 方法返回的是对已经存在的列表进行操作,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。 sorted 语法: ~~~ sorted(iterable, key=None, reverse=False) ~~~ 参数说明: * iterable -- 可迭代对象。 * key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。 * reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。 返回值:返回重新排序的列表。 ``` >>> lst = [3, 4, 1, 2, 6, 5, 9, 8, 7] >>> sorted(lst) [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst [3, 4, 1, 2, 6, 5, 9, 8, 7] >>> tup = (3, 5, 4, 2, 1) >>> sorted(tup) [1, 2, 3, 4, 5] >>> dic = {1: 'D', 2: 'C', 3: 'B', 4: 'A'} >>> sorted(dic) [1, 2, 3, 4] ``` —reverse():获得反向列表 ``` >>> lst = ['我', '爱', '她'] >>> lst.reverse() >>> lst ['她', '爱', '我'] ``` —list(range(stop)):生成0-stop的数字,隔1,不包含stop ``` >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` —列表解析: ``` >>> lst1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> lst2 = [i for i in lst1] >>> lst2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] ``` **列表推导式** *参考Python文档* > 列表推导式提供了一个更简单的创建列表的方法。常见的用法是把某种操作应用于序列或可迭代对象的每个元素上,然后使用其结果来创建列表,或者通过满足某些特定条件元素来创建子序列。 ——Python 文档 例如,假设我们想创建一个平方列表,像这样 ~~~ >>> squares = [] >>> for x in range(10): ... squares.append(x**2) ... >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] ~~~ 注意这里创建(或被重写)的名为`x`的变量在for循环后仍然存在。我们可以计算平方列表的值而不会产生任何副作用 ~~~ squares = list(map(lambda x: x**2, range(10))) ~~~ 或者,等价于 ~~~ squares = [x**2 for x in range(10)] ~~~ 上面这种写法更加简洁易读。 列表推导式的结构是由一对方括号所包含的以下内容:一个表达式,后面跟一个`for`子句,然后是零个或多个`for`或`if`子句。 其结果将是一个新列表,由对表达式依据后面的`for`和`if`子句的内容进行求值计算而得出。 举例来说,以下列表推导式会将两个列表中不相等的元素组合起来: ~~~ >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ~~~ 而它等价于 ~~~ >>> combs = [] >>> for x in [1,2,3]: ... for y in [3,1,4]: ... if x != y: ... combs.append((x, y)) ... >>> combs [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)] ~~~ 注意在上面两个代码片段中,`for` 和`if`的顺序是相同的。 如果表达式是一个元组(例如上面的`(x,y)`),那么就必须加上括号 ~~~ >>> vec = [-4, -2, 0, 2, 4] >>> # create a new list with the values doubled >>> [x*2 for x in vec] [-8, -4, 0, 4, 8] >>> # filter the list to exclude negative numbers >>> [x for x in vec if x >= 0] [0, 2, 4] >>> # apply a function to all the elements >>> [abs(x) for x in vec] [4, 2, 0, 2, 4] >>> # call a method on each element >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [weapon.strip() for weapon in freshfruit] ['banana', 'loganberry', 'passion fruit'] >>> # create a list of 2-tuples like (number, square) >>> [(x, x**2) for x in range(6)] [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)] >>> # the tuple must be parenthesized, otherwise an error is raised >>> [x, x**2 for x in range(6)] File "<stdin>", line 1, in <module> [x, x**2 for x in range(6)] ^ SyntaxError: invalid syntax >>> # flatten a list using a listcomp with two 'for' >>> vec = [[1,2,3], [4,5,6], [7,8,9]] >>> [num for elem in vec for num in elem] [1, 2, 3, 4, 5, 6, 7, 8, 9] ~~~ 列表推导式可以使用复杂的表达式和嵌套函数 ~~~ >>> from math import pi >>> [str(round(pi, i)) for i in range(1, 6)] ['3.1', '3.14', '3.142', '3.1416', '3.14159'] ~~~ **列表作为栈使用** *参考Python文档* 列表方法使得列表作为堆栈非常容易,最后一个插入,最先取出(“后进先出”)。要添加一个元素到堆栈的顶端,使用`append()`。要从堆栈顶部取出一个元素,使用`pop()`,不用指定索引。例如 ~~~ >>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4] ~~~ **列表作为队列使用** *参考Python文档* 列表也可以用作队列,其中先添加的元素被最先取出 (“先进先出”);然而列表用作这个目的相当低效。因为在列表的末尾添加和弹出元素非常快,但是在列表的开头插入或弹出元素却很慢 (因为所有的其他元素都必须移动一位)。 若要实现一个队列,`collections.deque` 被设计用于快速地从两端操作。例如 ~~~ >>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham']) ~~~ **** # 2.6 字典 字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值(key=>value)对用冒号( **:** )分割,每个对之间用逗号( **,** )分割,整个字典包括在花括号( **{}** )中 ,格式如下所示: ~~~ d = {key1 : value1, key2 : value2 } ~~~ 键必须是唯一的,但值则不必。 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 一个简单的字典实例: ~~~ dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} ~~~ 也可如此创建字典: ~~~ dict1 = { 'abc': 456 } dict2 = { 'abc': 123, 98.6: 37 } ~~~ **访问字典的值** 通过键访问值 ``` >>> dict1 = {1: 'Jack', 2: 'Joe', 3: 'Maria'} >>> dict1[2] 'Joe' ``` 访问的不存在的键将出错: ``` >>> dic = {1: 'Jack', 2: 'Joe', 3: 'Maria'} >>> dic[4] Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> dic[4] KeyError: 4 ``` **修改字典** 添加新的键值对,修改原有键值对 ``` >>> dic = {'Name': 'Hicoder', 'Age': '24', 'College': 'Stanford University'} >>> dic['Hobby'] = 'Basketball' >>> dic {'Name': 'Hicoder', 'Age': '24', 'College': 'Stanford University', 'Hobby': 'Basketball'} >>> dic['Age'] = 18 >>> dic {'Name': 'Hicoder', 'Age': 18, 'College': 'Stanford University', 'Hobby': 'Basketball'} ``` **删除字典元素** ``` >>> dic = {'Name': 'Hicoder', 'Age': '24', 'College': 'Stanford University'} >>> del dic['College'] >>> dic {'Name': 'Hicoder', 'Age': '24'} >>> del dic >>> dic Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> dic NameError: name 'dic' is not defined ``` **清空字典** dict.clear() ``` >>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'} >>> dic.clear() >>> dic {} ``` **复制字典一个副本** ``` >>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'} >>> dic_1 = dic.copy() >>> dic_1 {'name': 'Adam', 'age': 18, 'hobby': 'running'} ``` **遍历字典** 遍历键值对: ``` >>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'} >>> for k, v in dic.items(): \ print(k, v) name Adam age 18 hobby running ``` 遍历键: ``` >>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'} >>> for k in dic: \ print('key:', k) key: name key: age key: hobby >>> for k in dic.keys(): \ print('key:', k) key: name key: age key: hobby ``` 遍历值: ``` >>> dic = {'name': 'Adam', 'age': 18, 'hobby': 'running'} >>> for v in dic.values(): \ print('value:', v) value: Adam value: 18 value: running ``` **嵌套** 字典列表:在列表中嵌套字典,由多个字典组成的列表 ``` >>> dic1 = {'name': 'Adam', 'age': 18, 'hobby': 'running'} >>> dic2 = {'name': 'Jack', 'age': 19, 'hobby': 'basketball'} >>> dic3 = {'name': 'Joe', 'age': 18, 'hobby': 'Pingpong'} >>> student_info = [dic1, dic2, dic3] >>> for std_info in student_info: \ print(std_info) {'name': 'Adam', 'age': 18, 'hobby': 'running'} {'name': 'Jack', 'age': 19, 'hobby': 'basketball'} {'name': 'Joe', 'age': 18, 'hobby': 'Pingpong'} ``` (以下两个例子摘自埃里克·玛瑟斯《Python编程从入门到实践》) 在字典中嵌套列表,适用于需要一个键关联多个值时: ``` favorite_languages = {'Jen': ['Python', 'Ruby'], 'Sarah': ['C'], 'Edward': ['C++', 'JS']} for name, languages in favorite_languages.items(): print("\n" + name.title() + "'s favorite languages are:") for language in languages: print("\t" + language.title()) ``` ``` # Out: Jen's favorite languages are: Python Ruby Sarah's favorite languages are: C Edward's favorite languages are: C++ Js ``` 字典嵌套字典: ``` users = { 'aeinstein': { 'first': 'albert', 'last': 'einstein', 'location': 'princeton', }, 'mcurie': { 'first': 'marie', 'last': 'curie', 'location': 'paris', }, } for username, user_info in users.items(): print("\nUsername: " + username) full_name = user_info['first'] + " " + user_info['last'] location = user_info['location'] print("\tFull name: " + full_name.title()) print("\tLocation: " + location.title()) ``` ``` # Out: Username: aeinstein Full name: Albert Einstein Location: Princeton Username: mcurie Full name: Marie Curie Location: Paris ``` **** # 2.7 集合 **集合**(set)是一个无序的不重复元素序列。 可以使用大括号{ }或者set()函数创建集合,注意:创建一个空集合必须用set()而不是{ },因为{ }是用来创建一个空字典。 ``` >>> basket = {'banana', 'apple', 'orange', 'pear'} >>> type(basket) <class 'set'> >>> set_chr = set('hello python') >>> set_chr {'p', 'o', ' ', 'n', 'l', 'h', 't', 'e', 'y'} >>> # 剔除重复元素 >>> ball = {'basketball', 'football', 'table tennis', 'tennis', 'basketball', 'tennis'} >>> ball {'basketball', 'table tennis', 'tennis', 'football'} ``` **集合适用的操作符** | 操作符 | 解释 | | -- | -- | | in | 判断包含关系 | | not in | 判断不包含关系 | | ==、!=、>、<、>=、<=、 | 比较操作符 | ``` >>> sample1 = {1, 2, 3, 4, 5, 6, 7, 8} >>> sample2 = {3, 2, 4, 5, 7, 9, 10} >>> 6 in sample1 True >>> 11 not in sample2 True >>> sample1 >= sample2 False ``` **集合运算** ``` >>> a = set('abcdgklrt') >>> b = set('abdkgehrkls') >>> # 并集 OR >>> a | b {'b', 'l', 'e', 'r', 'd', 'a', 'g', 's', 'h', 'c', 'k', 't'} >>> # 交集 AND >>> a & b {'b', 'd', 'g', 'k', 'l', 'r', 'a'} >>> # 差集 >>> a - b {'t', 'c'} >>> # 对称差分 XOR >>> a ^ b {'h', 's', 'c', 't', 'e'} ``` **内置函数** 添加元素: ``` >>> a_set = {5, 2, 0, 'Python', 'Lover'} >>> # set.add(obj) 添加新元素 >>> a_set.add('China') >>> a_set {0, 'China', 2, 5, 'Python', 'Lover'} >>> # set.update(seq) 用序列更新集合,序列的每个元素都被添加到集合中 >>> a_set.update('Ilove') >>> a_set {0, 'China', 2, 5, 'o', 'v', 'e', 'Python', 'Lover', 'I', 'l'} ``` 删除元素: ``` >>> b_set = {'I', 'Love', 'You', 'Python', 'China', 'Jane'} >>> # set.remove(key):删除指定的key >>> b_set.remove('I') >>> b_set {'China', 'You', 'Jane', 'Python', 'Love'} >>> b_set.remove('English') Traceback (most recent call last): File "<pyshell#43>", line 1, in <module> b_set.remove('English') KeyError: 'English' >>> # set.discard(obj):若obj存在,则删除它 >>> b_set.discard('World') >>> b_set {'China', 'You', 'Jane', 'Python', 'Love'} >>> b_set.discard('You') >>> b_set {'China', 'Jane', 'Python', 'Love'} >>> # set.pop():删除任意一个元素 >>> b_set {'China', 'Jane', 'Python', 'Love'} >>> b_set.pop() 'China' >>> b_set {'Jane', 'Python', 'Love'} ``` **** # 2.8 操作符优先级 有括号,先括号。 | 操作符 | 描述 | | --- | --- | | \*\* | 指数 (最高优先级) | | ~ + - | 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@) | | \* / % // | 乘,除,取模和取整除 | | \+ - | 加法减法 | | \>> << | 右移,左移运算符 | | & | 位 'AND' | | ^ \| | 位运算符 | | >= | 比较运算符 | | <> == != | 等于运算符 | | \= %= /= //= -= += \*= \*\*= | 赋值运算符 | | is is not | 身份运算符 | | in not in | 成员运算符 | | and or not | 逻辑运算符 |