1.数字类型
数字是不可更改类型,直接访问。主要用于计算、运算。
1.1常见方法。
bit_length
''' | bit_length(...) | int.bit_length() -> int | | Number of bits necessary to represent self in binary. '输出该数字的二进制表示方式所占的位数' ''' # 例 for i in range(5): print('数字%d占二进制位数为%d' % (i, i.bit_length())) ''' 结果 数字0占二进制位数为0 数字1占二进制位数为1 数字2占二进制位数为2 数字3占二进制位数为2 数字4占二进制位数为3 二进制 十进制 0000 0000 0 0000 0001 1 0000 0010 2 0000 0011 3 0000 0100 4 '''
1.2 python进制的转化
# binary 二进制 # octal 八进制 # hex 十六进制 a = 10 print(bin(a)) # 0b1010 # 十进制的数转换成二进制的数,0o开头就是二进制的数字 # 0 1 10 11 print(oct(a)) # 0o12 # 十进制的数转换成八进制的数,0o开头就是八进制的数字 # 1 2 3 4 5 6 7 print(hex(a)) # 0xa # 十进制的数转换成十六进制的数,0o开头就是十六进制的数字 # 0 1 2 3 4 5 6 7 8 9 a b c d e f print(int('10010', base=2)) # 18 print(int('10010', base=10)) # 10010 print(int('10010', base=8)) # 4104 print(int('10010', base=16)) # 65552
2.布尔值bool
布尔值就两种:True,False。就是反应条件的正确与否。
''' 下列对象的布尔值是False None False(布尔类型) 所有的值为零的数 0(整型) 0.0+0.0(复数) ''(空字符串) [](空列表) {}(空字典) ()(空元组) '''
3.序列sequence
3.1序列介绍
在python中,序列有着相同访问模式:它的每一个元素可以通过指定一个下标的方式获得。而多个元素可以通过切片操作的方式一次得到,下标是从0开始到总元素数(序列的长度)-1结束。常见的序列有字符串、列表、元组。
3.2序列操作符
seq = 'What is you name?' # 成员操作符(in、not in) print('w' in seq) # False print('w' not in seq) # True # 链接操作符(+) seq = seq + ' python' print(seq) # What is you name? python # 重复操作符(*) seq = seq * 2 print(seq) # What is you name? pythonWhat is you name? python
3.3序列索引与切片
索引
# 根据下标打印相应内容 s = 'python自动化运维21期' for i in range(len(s)): print(i, s[i]) # 0 p # 1 y # 2 t # 3 h # ... # 12 1 # 13 期
切片
# 序列的切片,下标(索引)范围为0...序列长度-1,遵循顾头不顾尾的原则,如果开始为0或结束为序列长度-1,可以不写 # s[起始索引:结束索引+1:步长] # 正向打印字符串 print(s[:]) # python自动化运维21期 print(s[6:9]) # 自动化 # 可以按步长取值,步长必须保持一致,不能变化 print(s[0:9:2]) # pto自化 # 反向打印字符串 print(s[::-1]) # 期12维运化动自nohtyp
4.字符串类型
可以通过在引号间包含字符的方式创建,可存储少量数据,是不可更改类型。python中的单引号和双引号作用是相同的。


# 1.capitalize与titile ''' capitalize 1)翻译 英 [ˈkæpɪtəlaɪz] 美 [ˈkæpɪtl:ˌaɪz] vt.用大写字母写或印刷;使…资本化;估计…的价值;把…定为首都 vi.利用;积累资本 2)源码注释 | capitalize(...) | S.capitalize() -> str | | Return a capitalized version of S, i.e. make the first character | have upper case and the rest lower case. 3)作用 字符串首字母大写,其余全部小写 ''' # 例 s = 'lemon TREE' s1 = s.capitalize() print(s1) # Lemon tree ''' title 1)翻译 title 英 [ˈtaɪtl] 美 [ˈtaɪtl] n.标题;头衔;[体]冠军;[影视]字幕 vt.加标题;赋予头衔;把…称为 adj.标题的;冠军的;头衔的 2)源码注释 | title(...) | S.title() -> str | | Return a titlecased version of S, i.e. words start with title case | characters, all remaining cased characters have lower case. 3)作用 字符串中每个单词的首字母大写,其余字母都小写 ''' # 例 s = 'lemon TREE' s2 = s.title() print(s2) # Lemon Tree # 2.upper与lower # *** upper(), lower() 全部大写,全部小写,在编写输入验证码时比较常见 ''' 1)翻译 upper 英 [ˈʌpə(r)] 美 [ˈʌpɚ] adj.上面的;地位较高的;内地的;地表层的 n.鞋帮,靴面;兴奋剂;令人兴奋的经历 2)源码解释 | upper(...) | S.upper() -> str | | Return a copy of S converted to uppercase. 3)作用 字符串字母全部大写 ''' # 例 s = 'lemon TREE' s3 = s.upper() print(s3) # LEMON TREE ''' 1)翻译 lower 英 [ˈləʊə(r)] 美 [ˈloʊə(r)] adj.下方的;在底部的;较低级的 v.降低;减少;缩小 2)源码解释 | lower(...) | S.lower() -> str | | Return a copy of the string S converted to lowercase. 3)作用 字符串字母全部小写 ''' s = 'lemon TREE' s5 = s.lower() print(s5) # lemon tree # 3.* 大小写反转 swapcase() ''' 1)翻译 swap 英 [swɒp] 美 [swɑp] n.交换;交换物,被掉换者 vi.交换(工作) vt.用…替换,把…换成,掉换(过来) case 英 [keɪs] 美 [kes] n.(实)例,事例;情况,状况;诉讼(事件),案件,判例;容器(箱,盒) vt.把…装入箱(或盒等)内;加盖于;包围,围住;[俚语](尤指盗窃前)探察,侦查,窥测 2)源码解释 | swapcase(...) | S.swapcase() -> str | | Return a copy of S with uppercase characters converted to lowercase | and vice versa. 3)作用 将字符串的大小写翻转 ''' # 例 s = 'lemon TREE' s6 = s.swapcase() print(s6) # LEMON tree # 4.居中center(),左对齐ljust(),右对齐rjust(), zfill() ''' 1)翻译 center 英 ['sentə] 美 [ˈsɛntɚ] n.中心;中枢;(球队的) 中锋;中心区 adj.中央的,位于正中的;(在)中心的 vt.集中;使聚集在一点;定中心;居中 vi.居中,有中心,被置于中心 2)源码解释 | center(...) | S.center(width[, fillchar]) -> str | | Return S centered in a string of length width. Padding is | done using the specified fill character (default is a space) 相关单词:fillchar == fill character fill 英 [fɪl] 美 [fɪl] vt.& vi.(使)充满,(使)装满 vt.满足;配药;(按订单)供应;使充满(感情) n.填满…的量;充分;装填物;路堤 character 英 [ˈkærəktə(r)] 美 [ˈkærəktɚ] n.性格;角色;特点;字母 vt.刻,印;使具有特征 3)作用 居中,长度自己设定,默认填充物是None,space,填充物必须是单个字符,不可以是int、bool等 ''' # 例 s = 'lemon TREE' s7 = s.center(30) print(s7) # lemon TREE s8 = s.center(30, '-') print(s8) # ----------lemon TREE---------- ''' ljust == left-justified 1)翻译 英 ['leftdʒ'ʌstɪfaɪd] 美 ['leftdʒ'ʌstɪfaɪd] v.左对齐( left-justify的过去式和过去分词 ) 2)源码解释 | ljust(...) | S.ljust(width[, fillchar]) -> str | | Return S left-justified in a Unicode string of length width. Padding is | done using the specified fill character (default is a space). 3)作用 左对齐,长度自己设定必须添加,否则会报错,默认填充物是space,填充物必须是单个字符,不可以是int、bool等 TypeError: ljust() takes at least 1 argument (0 given) ''' # 例 s = 'lemon TREE' s9 = s.ljust(20) print(s9) # lemon TREE s10 = s.ljust(20, '-') print(s10) # lemon TREE---------- ''' rjust == right-justified 1)翻译 英 ['raɪtdʒ'ʌstɪfaɪd] 美 ['raɪtdʒ'ʌstɪfaɪd] [计] 右对齐的 2)源码解释 | rjust(...) | S.rjust(width[, fillchar]) -> str | | Return S right-justified in a string of length width. Padding is | done using the specified fill character (default is a space). 3)作用 右对齐,长度自己设定,默认填充物是None,space,填充物必须是单个字符,不可以是int、bool等 ''' # 例 s = 'lemon TREE' s11 = s.rjust(20) print(s11) # lemon TREE s12 = s.rjust(20, '-') print(s12) # ----------lemon TREE ''' zfill 1)翻译 zfill == zero fill 2)源码解释 | zfill(...) | S.zfill(width) -> str | | Pad a numeric string S with zeros on the left, to fill a field | of the specified width. The string S is never truncated. 3)作用 zfill方法返回指定长度的字符串,原字符串右对齐,前面填充0。 ''' #例 s = 'lemon TREE' s13 = s.zfill(20) print(s13) # 0000000000lemon TREE # 5.以...开始startswith()、以...结束endswith() ''' startswith 1)翻译 以...开始 2)源码解释 | startswith(...) | S.startswith(prefix[, start[, end]]) -> bool | | Return True if S starts with the specified prefix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | prefix can also be a tuple of strings to try. 3)作用 检查字符串是否是以相应字符串开头,是则返回 True,否则返回 False。如果开始和结束指定值,则在指定范围内检查。 ''' # 例 s = 'lemon TREE' print(s.startswith('a')) # False print(s.startswith('lemon')) # True print(s.startswith('lemon TREE')) # True print(s.startswith('lemon TREE', 0,-1)) # False print(s.startswith('lemon TREE', 0,)) # True ''' endswith 1)翻译 以...结束 2)源码解释 | endswith(...) | S.endswith(suffix[, start[, end]]) -> bool | | Return True if S ends with the specified suffix, False otherwise. | With optional start, test S beginning at that position. | With optional end, stop comparing S at that position. | suffix can also be a tuple of strings to try. 3)作用 检查字符串是否是以相应字符串结束,是则返回 True,否则返回 False。如果开始和结束指定值,则在指定范围内检查。 ''' # 例 s = 'lemon TREE' print(s.endswith('E')) # True print(s.endswith('e')) # False print(s.endswith('lemon TREE')) # True print(s.endswith('lemon TREE', 0, -1)) # False print(s.endswith('lemon TREE', 0)) # True # 6.去除空格,制表符,换行符strip()/lstrip()/rstrip() ''' strip 1)翻译 英 [strɪp] 美 [strɪp] vi.剥光;剥除 vt.除去,剥去;剥夺;删除;清除,拆除 n.长条,条板;带状地带(或森林、湖面等);(足球队员的)运动服 2)源码解释 | strip(...) | S.strip([chars]) -> string or unicode | | Return a copy of the string S with leading and trailing | whitespace removed. | If chars is given and not None, remove characters in chars instead. | If chars is unicode, S will be converted to unicode before stripping 3)作用 去除首尾的空格,制表符\t,换行符,项目中必须添加。可以填加填充物,多个字符表示迭代着去,前后去t->e->y lstrip()/rstrip()用法类似 ''' # 例 s = ' \tlemon tree\n' s14 = s.strip() print(s14) # lemon tree # 迭代着去除,先去除'-',再去除'+',再去除'*' s = '--++**lemon tree**++--' s15 = s.strip('-+*') print(s15) # lemon tree # 7.分割字符串split()/rsplit() ''' split 1)翻译 英 [splɪt] 美 [splɪt] vt.分裂;分开;<俚>(迅速)离开;分担 n.划分;分歧;裂缝;劈叉 vi.<俚>走开;揭发;被撞碎;<美>[证券](股票)增加发行 adj.裂开的,劈开的,分离的,分裂的 2)源码解释 | split(...) | S.split([sep [,maxsplit]]) -> list of strings | | Return a list of the words in the string S, using sep as the | delimiter string. If maxsplit is given, at most maxsplit | splits are done. If sep is not specified or is None, any | whitespace string is a separator and empty strings are removed | from the result. 3)作用 以seq为分隔符截取字符串,默认按照空格分割,可以添加分割字符的个数,如果是2,则返回的列表有三个元素 ''' # 例 s = 'lemon TREE' s16 = s.split() print(s16) # ['lemon', 'TREE'] s = 'lemonTREE' s17 = s.split() print(s17) # ['lemonTREE'] # 如果分割符在开始,返回列表则添加''元素 s = 'oldboyowusiroalex' s18 = s.split('o') print(s18) # ['', 'ldb', 'y', 'wusir', 'alex'] # 添加分割字符的个数,如果是2,则返回的列表有三个元素 s19 = s.split('o', 2) print(s19) # ['', 'ldb', 'yowusiroalex'] # rstrip()从右向左分割 ''' rstrip 1)翻译 right split 2)源码解释 | rsplit(...) | S.rsplit(sep=None, maxsplit=-1) -> list of strings | | Return a list of the words in S, using sep as the | delimiter string, starting at the end of the string and | working to the front. If maxsplit is given, at most maxsplit | splits are done. If sep is not specified, any whitespace string | is a separator. 3)作用 用法和split相同,只不过是从右向左分割 ''' # 例 s = 'oldboyowusiroalex' s20 = s.rsplit('o', 2) print(s20) # ['oldboy', 'wusir', 'alex'] # 8.连接字符串join() ''' join 1)翻译 英 [dʒɔɪn] 美 [dʒɔɪn] vt.& vi.加入;参加;连接;联结 vt.参与;结合;上(火车、飞机等);上(路) n.连接;结合;接合处;接合点 2)源码解释 | join(...) | S.join(iterable) -> str | | Return a string which is the concatenation of the strings in the | iterable. The separator between elements is S. 3)作用 以指定字符串作为分隔符,将字符串中所有的元素(的字符串表示)合并为一个新的字符串,也可以在列表中使用 ''' # 例 s = 'lemon TREE' s21 = '-*-'.join(s) print(s21) # l-*-e-*-m-*-o-*-n-*- -*-T-*-R-*-E-*-E l = ['lemon', 'tree'] s22 = '-*-'.join(l) print(s22) # lemon-*-tree # 9.替换replace() ''' replace 1)翻译 英 [rɪˈpleɪs] 美 [rɪˈples] vt.代替;替换;把…放回原位;(用…)替换 2)源码解释 | replace(...) | S.replace(old, new[, count]) -> str | | Return a copy of S with all occurrences of substring | old replaced by new. If the optional argument count is | given, only the first count occurrences are replaced. 3)作用 (老的,新的,次数(什么都不写为全部替换)) 将字符串中的str1替换成str2,如果count指定,则替换不超过count次。 ''' # 例 s = 'lemon tree' s23 = s.replace('e', 'E') print(s23) # lEmon trEE # 只把'e'替换成'E'两次 s24 = s.replace('e', 'E', 2) print(s24) # lEmon trEe # 10.搜索find()/index() ''' find 1)翻译 英 [faɪnd] 美 [faɪnd] v.找到;发现;查明;发觉 n.发现物;被发现的人 2)源码解释 | find(...) | S.find(sub[, start[, end]]) -> int | | Return the lowest index in S where substring sub is found, | such that sub is contained within S[start:end]. Optional | arguments start and end are interpreted as in slice notation. | | Return -1 on failure. 3)作用 检测sub是否包含在字符串中,如果指定范围start和end,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1 ''' # 例 s = 'lemon tree' print(s.find('e')) # 1 print(s.find('E')) # -1 # 如果是多个字符的字符串,输入匹配到的字符的第一个字符的下标 print(s.find('tree')) # 6 print(s.find('lemon', 0)) # 0 print(s.find('tree', 0, 6)) # -1 ''' index 1)翻译 英 [ˈɪndeks] 美 [ˈɪnˌdɛks] n.索引;<数>指数;指示;标志 vt.给…编索引;把…编入索引;[经济学]按生活指数调整(工资、价格等) vi.[机械学]转位 2)源码解释 | index(...) | S.index(sub[, start[, end]]) -> int | | Like S.find() but raise ValueError when the substring is not found. 3)作用 检测sub是否包含在字符串中,如果指定范围start和end,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则会报错 ''' # 例 s = 'lemon tree' print(s.index('e')) # 1 # ind = s.index('XX') # print(ind) # ind = s.index('XX') # ValueError: substring not found # 11.格式化输出format() ''' format 1)翻译 英 [ˈfɔ:mæt] 美 [ˈfɔ:rmæt] n.(出版物的)版式;[自](数据安排的)形式;电视节目的总安排(或计划) vt.使格式化;安排…的格局;设计…的版面 vi.设计一个版式 2)源码解释 | format(...) | S.format(*args, **kwargs) -> str | | Return a formatted version of S, using substitutions from args and kwargs. | The substitutions are identified by braces ('{' and '}'). 3)作用 用于字符串的格式化 ''' # 例 # 通过站位符输出 s25 = '这是{}的{}个{}'.format('我', '第一', '博客') print(s25) # 这是我的第一个博客 # 通过位置输出,便于输出带有重复字符的字符串 s26 = '这是{0}的{1}个{2},欢迎大家光临我的{2}'.format('我', '第一', '博客') print(s26) # 这是我的第一个博客,欢迎大家光临我的博客 # 通过关键字输出 s27 = '这是{who}的{num}个{what}'.format(who='我', num='第一', what='博客') print(s27) # 这是我的第一个博客 # 12.公共方法len()/count() ''' len == length 1)翻译 length 英 [leŋθ] 美 [leŋθ] n.长度,长;时间的长短;(语)音长;一段,一节 2)源码解释 len(obj, /) Return the number of items in a container. 3)作用 返回序列的长度 ''' # 例 s = 'lemon tree' print(len(s)) # 10 ''' count 1)翻译 英 [kaʊnt] 美 [kaʊnt] n.总数;数数;罪状;论点 v.数数;计算总数;把…算入;重要 2)源码解释 | count(...) | S.count(sub[, start[, end]]) -> int | | Return the number of non-overlapping occurrences of substring sub in | string S[start:end]. Optional arguments start and end are | interpreted as in slice notation. 3)作用 统计sub在字符串中出现的次数,可以添加范围 ''' s = 'lemon tree' s28 = s.count('e') print(s28) # 3 s29 = s.count('E') print(s29) # 0 # 13.is系列 ''' isalnum = is alphanumeric 1)翻译 英 [ˌælfənju:ˈmerɪk] 美 [ˌælfənu:ˈmerɪk] adj.文字数字的,包括文字与数字的 2)源码解释 | isalnum(...) | S.isalnum() -> bool | | Return True if all characters in S are alphanumeric | and there is at least one character in S, False otherwise. 3)作用 判断字符串是否仅由字母或数字且至少一个由数字或者字母组成 ''' # 例 s30 = '1' print(s30.isalnum()) # True s31 = 'a' print(s31.isalnum()) # True s32 = '1a' print(s32.isalnum()) # True s33 = '' print(s33.isalnum()) # False s34 = '+1' print(s34.isalnum()) # False ''' isalpha = is alphabetic 1)翻译 英 [ˌælfəˈbetɪk] adj.照字母次序的,字母的 2)源码解释 | isalpha(...) | S.isalpha() -> bool | | Return True if all characters in S are alphabetic | and there is at least one character in S, False otherwise. 3)作用 判断字符串是否仅由字母且至少一个字母组成 ''' # 例 s35 = 's+' print(s35.isalpha()) # False s36 = 's6' print(s36.isalpha()) # False s37 = 's' print(s37.isalpha()) # True ''' isdigit = is digit 1)翻译 英 [ˈdɪdʒɪt] 美 [ˈdɪdʒɪt] n.数字;手指,足趾;一指宽 2)源码解释 | isdigit(...) | S.isdigit() -> bool | | Return True if all characters in S are digits | and there is at least one character in S, False otherwise. 3)作用 判断字符串是否仅由字母且至少一个数字组成 ''' # 例 s38 = '5' print(s38.isdigit()) # True s39 = '5s' print(s39.isdigit()) # False s40 = '5+' print(s40.isdigit()) # False
5.列表list
容器型数据类型,可变数据类型。可以包含数字、布尔值、字符串、列表、元组、字典、集合等元素,例如:[True, 1, 'name', {'name': 'oldboy'}, [1, 2, 3], (2, 3, 4), set(1, 2, 3)],可以进行检索和索引等操作
5.1增删改查
增:
# 1.在列表末尾添加新的对象append ''' append 1)翻译 英 [əˈpend] 美 [əˈpɛnd] vt.附加;添加;贴上;签(名) 2)源码注释 | append(...) | L.append(object) -> None -- append object to end 3)作用 在列表末尾添加新的对象 ''' # 例 l = [1, 2, 3, 4] l.append(5) print(l) # [1, 2, 3, 4, 5] # 这个是一个动作,没有返回值,所以是None print(l.append(6)) # None # 2.按照索引插入insert ''' insert 1)翻译 英 [ɪnˈsɜ:t] 美 [ɪnˈsɜ:rt] vt.插入;嵌入;(在文章中)添加;加插 n.插入物;添入物(尤指一页印刷品图中插入或套印的小图);(书报的)插页;添加物 2)源码注释 | insert(...) | L.insert(index, object) -- insert object before index 3)作用 在索引的前面插入对象 ''' # 例 l = ['apple', 'banana', 'orange'] l.insert(1, 'pear') print(l) # ['apple', 'pear', 'banana', 'orange'] # 3.迭代着增加extend ''' extend 1)翻译 英 [ɪkˈstend] 美 [ɪkˈstɛnd] vt.& vi.延伸;扩大;推广 vt.延长;伸展;给予;发出(邀请、欢迎等) vi.延伸;伸出;增加 2)源码注释 | extend(...) | L.extend(iterable) -> None -- extend list by appending elements from the iterable 3)作用 迭代着增加,把序列分解成最小元素添加到原列表的结尾 ''' # 例 l1 = ['a', 'b', 'c'] l2 = ['d', 'e', 'f'] l1.extend(l2) print(l1) print(l2) # ['a', 'b', 'c', 'd', 'e', 'f'] # ['d', 'e', 'f'] l2.extend('567') print(l2) # ['d', 'e', 'f', '5', '6', '7'] '''
删:
# 1.有返回值的删除pop() ''' pop 1)说明 有返回值的删除 2)源码解释 | L.pop([index]) -> item -- remove and return item at index (default last). | Raises IndexError if list is empty or index is out of range. 3)作用 用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。 ''' # 例 # 不添加下标删除,默认列表最后一个元素 l = ['a', 'b', 'c', 'd'] l.pop() print(l) # ['a', 'b', 'c'] # 根据下标删除列表的元素 l = ['a', 'b', 'c', 'd'] l.pop(1) print(l) # ['a', 'c', 'd'] # 有返回值,可以看到删除的元素 l = ['a', 'b', 'c', 'd'] print(l.pop(1)) # b # 2.按照元素删除remove() ''' remove 1)翻译 英 [rɪˈmu:v] 美 [rɪˈmuv] vt.去除;开除;脱掉,拿下;迁移 vi.迁移,移居;离开 n.距离,差距;移动 2)源码解释 | L.remove(value) -> None -- remove first occurrence of value. | Raises ValueError if the value is not present. 3)作用 根据元素删除,如果不添加参数会报错 ''' # 例 l = ['a', 'b', 'c', 'd'] l.remove('d') print(l) # ['a', 'b', 'c'] # 3.清空列表clear() ''' clear 1)源码解释 L.clear() -> None -- remove all items from L 2)作用 清空列表,返回一个空列表 ''' # 例 l = ['a', 'b', 'c', 'd'] l.clear() print(l) # [] # 4.内存级别删除del ''' del -- delete 删除 内存级别删除 ''' l = ['a', 'b', 'c', 'd'] del l print(l) # NameError: name 'l' is not defined
改:
# 1.按照索引修改 l = ['a', 'b', 'c', 'd'] l[2] = 'e' print(l) # ['a', 'b', 'e', 'd'] # 2.按照切片修改 l = ['a', 'b', 'c', 'd'] l[1:3] = [1, 2] print(l) # ['a', 1, 2, 'd']
查:
# 1.按照索引查看列表元素 l = ['a', 'b', 'c', 'd'] print(l[0]) # a # 2.按照切片查看列表元素 l = ['a', 'b', 'c', 'd'] print(l[2:4]) # ['c', 'd'] print(l[::2]) # ['a', 'c'] # 3.循环查看列表 l = ['a', 'b', 'c', 'd'] for i in l: print(i) # a # b # c # d
5.2其他方法:
# 1.统计列表中元素个数count l = ['a', 'b', 'c', 'd', 'a'] print(l.count('a')) # 2 # 2.统计列表长度len l = ['a', 'b', 'c', 'd', 'a'] print(len(l)) # 5 # 3.查找元素下标index,输出列表中第一个出现该元素的下标 l = ['a', 'b', 'c', 'd', 'a'] ind = l.index('a') print(ind) # 0 ind = l.index('f') # ValueError: 'f' is not in list # 4.排序sort # 从大到小 l = ['c', 'd', 'a', 'b'] l.sort(reverse=True) print(l) # 从小到大 l = ['c', 'd', 'a', 'b'] l.sort(reverse=False) print(l) # ['a', 'b', 'c', 'd'] # 默认从小到大 l = ['c', 'd', 'a', 'b'] l.sort() print(l) # ['a', 'b', 'c', 'd'] # 5.反向输出列表 l = ['c', 'd', 'a', 'b'] l.reverse() print(l) # ['b', 'a', 'd', 'c'] # 6.列表的嵌套 l = [1, 2, 3, [4, 5, 6]] print(l[3][2]) # 6
6.字典dict
6.1介绍
字典典的key是唯一的。key 必须是不可变的数据类型。
key:不可变的数据类型(可哈希):str,bool,tuple,int。
value:任意数据类型。
数据类型分类:
不可变的数据类型(可哈希):str,bool,tuple,int
可变的数据类型:dict,list,set。
容器类数据类型:list,tuple,dict,set.
字典:存储数据多,关系型数据,查询速度快(二分查找)。
3.6版本之前,字典是无序的,3.6之后字典是有序的。
6.2常见方法
创建字典:
# 创建字典 # 1. 创建空字典 dic = {} print(dic , type(dic)) # {} <class 'dict'> # 2. 直接赋值创建字典 dic = {'a': 1, 'b': 2, 'c': 3} print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 3. 通过关键字dict和关键字参数创建字典 dic = dict(a=1, b=2, c=3) print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 4. 通过二元组列表创建字典 lst = [('a', 1), ('b', 2), ('c', 3)] dic = dict(lst) print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 5. dict和zip结合创建字典 # 5.1 - 通过两个字符串创建字典 dic = dict(zip('abc', '123')) print(dic , type(dic)) # {'a': '1', 'b': '2', 'c': '3'} <class 'dict'> # 5.2 - 通过一个字符串、一个列表创建字典 dic = dict(zip('abc', [1,2,3])) print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 5.3 - 通过一个字符串、一个元组创建字典 dic = dict(zip('abc', (1,2,3))) print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 5.4 - 通过两个列表串创建字典 lst1 = ['a', 'b', 'c'] lst2 = [1, 2, 3] dic = dict(zip(lst1, lst2)) print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 5.5 - 通过两个列表串创建字典延伸 lst = ['a', 1, 'b', 2, 'c', 3] dic = dict(zip(lst[::2], lst[1::2])) print(dic , type(dic)) # {'a': 1, 'b': 2, 'c': 3} <class 'dict'> # 6. 通过字典推导式创建字典 dic = {i:2*i for i in range(3)} print(dic , type(dic)) # {0: 0, 1: 2, 2: 4} <class 'dict'> # 7. 通过dict.fromkeys()创建字典 # 通常用来初始化字典,设置value的默认值 dic = dict.fromkeys(range(3), 'x') print(dic , type(dic)) # {0: 'x', 1: 'x', 2: 'x'} <class 'dict'>
增:
# 1.有则覆盖,无则添加 dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} dic['high'] = 180 print(dic) # {'name': 'xiaoming', 'age': 30, 'hobby': 'games', 'high': 180} dic['name'] = 'ritian' print(dic) # {'name': 'ritian', 'age': 30, 'hobby': 'games', 'high': 180} # 2.有则不变,无则添加setdefault() # 无则添加 dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} dic.setdefault('high', 190) print(dic) # {'name': 'xiaoming', 'age': 30, 'hobby': 'games', 'high': 190} dic.setdefault('name', '日天') print(dic) # {'name': 'xiaoming', 'age': 30, 'hobby': 'games', 'high': 190}
删:
# 1.根据键删除对应值,有返回值pop() dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} print(dic.pop('name')) # xiaoming print(dic) # {'age': 30, 'hobby': 'games'} # 2.清空字典clear() dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} dic.clear() print(dic) # {} # 3.删除字典随机值,有返回值popitem() dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} print(dic.popitem()) # ('hobby', 'games') print(dic) # {'name': 'xiaoming', 'age': 30}
改:
# 1.直接更改 dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} dic['name'] = '小明' print(dic) # {'name': '小明', 'hobby': 'games', 'age': 30} # 2.字典更新update() dic1 = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} dic2 = {'weight': 75, 'high': 180, 'age': 31} # 将dic2中的键值对覆盖添加到dic1中 dic1.update(dic2) print(dic1) # {'name': 'xiaoming', 'age': 31, 'weight': 75, 'high': 180, 'hobby': 'games'}
查:
# 1.根据键查 dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} print(dic['name']) # xiaoming # 2.根据值查get() print(dic.get('name')) # xiaoming # 可以添加描述性语句 print(dic.get('high', '没有此键')) # 没有此键 # 3.循环打印键keys()/值values()/键值对items() # 打印键key() for i in dic.keys(): print(i) # name # hobby # age # 值values() for j in dic.values(): print(j) # xiaoming # games # 30 # 键值对items() for k in dic.items(): print(k) # ('name', 'xiaoming') # ('age', 30) # ('hobby', 'games')
其他方法:
# 1.字典长度len dic = {'name': 'xiaoming', 'age': 30, 'hobby': 'games'} print(len(dic)) # 3 # 2.fromkeys # dict.fromkeys(seq[, value]) # fromkeys函数用于创建一个新字典,以序列seq中元素做字典的键,value为字典所有键对应的初始值。 dic1 = dict.fromkeys('abc', 'name') print(dic1) # {'c': 'name', 'b': 'name', 'a': 'name'} dic2 = dict.fromkeys([1,2,3], 'id') print(dic2) # {1: 'id', 2: 'id', 3: 'id'} # 使用字典更改值的方法,其他键值对不会更改 dic2[1] = '序号' print(dic2) # 使用列表的追加方法,所有键的值都会更改 dic3 = dict.fromkeys('abc', []) print(dic3) # {'a': [], 'c': [], 'b': []} dic3['a'].append('apple') print(dic3) # {'b': ['apple'], 'c': ['apple'], 'a': ['apple']} # 3.字典的嵌套与列表的嵌套方式类似
7.元组tuple
元组是容器型数据类型,不可变数据类型,单元组的子元素的元素可以更改。
tu = (11, 2, True, [2,3,4], 'string') # 1.循环打印 for i in tu: print(i) # 11 # 2 # True # [2, 3, 4] # string # 2.索引打印 print(tu[1]) # 2 # 3.切片打印,打印结果还是元组 print(tu[:3:2]) # (11, True) # 4.查看元素下标 print(tu.index(True)) # 2 # 5.统计元素个数 print(tu.count(2)) # 1 # 6.统计元组长度 print(len(tu)) # 5 # 7.更改子元素的元素 tu[-2].append(666) print(tu) # (11, 2, True, [2, 3, 4, 666], 'string')
8.集合set
集合:无序,不重复的数据类型。它里面的元素必须是可哈希的,但是集合本身是不可哈希的。
python可哈希数据类型:数字、布尔值、字符串、元组
不可哈希数据类型:列表、字典
8.1定义集合
# 定义:数字、字符串、布尔值、元组 set1 = {1, 'string', False, (4, 5, 6)} print(set1) # {False, 1, (4, 5, 6), 'string'}
8.2可以用于列表的去重
# 列表去重 l1 = [1, 1, 2, 2, 3, 4, 5, 6] l2 = list(set(l1)) print(l2) # [1, 2, 3, 4, 5, 6]
8.3增、删
增
# 1.增add() set2 = {1, 'string', False, (4, 5, 6)} set2.add(666) print(set2) # {False, 1, 666, (4, 5, 6), 'string'} # 2.更新update(),将对象分割成最小元素添加到集合中 set2.update('abc') print(set2) # {False, 1, 'string', 'a', 'c', 'b', 666, (4, 5, 6)}
删
# 1.删除指定元素remove() set1 = {1, 'string', False, (4, 5, 6)} set1.remove(1) print(set1) # {False, 'string', (4, 5, 6)} # 2.随机删除一个元素pop() set1 = {1, 'string', False, (4, 5, 6)} set1.pop() print(set1) # {1, 'string', (4, 5, 6)} # 3.清空集合clear() set1 = {1, 'string', False, (4, 5, 6)} set1.clear() print(set1) # set() # 4.内存级删除集合del set1 = {1, 'string', False, (4, 5, 6)} del set1 print(set1)
# NameError: name 'set1' is not defined
8.4关系测试:交集、并集、差集、子集...
set1 = {1, 2, 3, 4, 5, 6} set2 = {5, 6, 7, 8, 9, 10} # 1.交集 & intersection # set1和set2共有的 print(set1 & set2) # {5, 6} print(set1.intersection(set2)) # {5, 6} # 2.并集 | union # set1+set2独有的 print(set1 | set2) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} print(set1.union(set2)) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} # 3.差集 - difference # set1有而set2没有 print(set1 - set2) # {1, 2, 3, 4} # 4.反交集 ^ symmetric_difference # set1中set2没有的+set2中set1没有的 print(set1 ^ set2) # {1, 2, 3, 4, 7, 8, 9, 10} print(set1.symmetric_difference(set2)) # {1, 2, 3, 4, 7, 8, 9, 10} # 5.子集 set1 = {1, 2, 3} set2 = {1, 2, 3, 4, 5, 6} # 判断set1是不是set2的子集 print(set1 < set2) # True print(set1.issubset(set2)) # True # 6.超集 # 判断set2是不是set1的超集 print(set2 > set1) # True print(set2.issuperset(set1)) # True # 7.不可变集合,冻集frozenset() set1 = frozenset('apple') print(set1) # frozenset({'p', 'a', 'l', 'e'}) print(type(set1)) # <class 'frozenset'>
9.数据类型的补充
# 1.按步长删除列表的值 # 最直接的方式del l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] del l[1::2] print(l) # [1, 3, 5, 7, 9] # 使用循环删除,但必须是倒序方式,因为顺序删除时,列表随之改变,会出错 l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i = len(l)-1 while i > 0: if i % 2 == 1: del l[i] i -= 1 print(l) # [1, 3, 5, 7, 9] l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in range(len(l1)-1,-1,-1): if i % 2 == 1: del l[i] print(l) # [1, 3, 5, 7, 9] # 2.range 可定制的数字列表 for i in range(4): print(i) # 0 # 1 # 2 # 3 for i in range(1,4): print(i) # 1 # 2 # 3 for i in range(1,5,2): print(i) # 1 # 3 # 反向取,必须添加步长 for i in range(4,1,-1): print(i) # 4 # 3 # 2 # 3.dict 再循环字典时,不要改变字典的大小。 dic = {'k1':'v1','k2':'v2','k3':'v3','r':666} l1 = [] # 循环字典,将字典中的键添加到列表中 for i in dic: if 'k' in i: l1.append(i) print(l1) # ['k2', 'k3', 'k1'] # 循环列表,删除字典中的键 for i in l1: del dic[i] print(dic) # 4.tu 如果元组里面只有一个元素并且没有逗号隔开,那么他的数据类型与该元素一致。 tu1 = (1) print(tu1,type(tu1)) # 1 <class 'int'> tu2 = ('string') print(tu2,type(tu2)) # string <class 'str'> tu3 = (['string',1,2]) print(tu3,type(tu3)) # ['string', 1, 2] <class 'list'>
10.小数据池,copy
# 1.对于赋值运算来说,相同值的变量指向的是同一个内存地址,所以他们完全是一样的。 a = 'string' b = 'string' print(a == b) # True print(a is b) # True print(id(a)) # 17922288 print(id(b)) # 17922288 # 2.python中的小数据池 # int -5~ 256的相同的数字全都指向一个内存地址,节省空间 # str:s = 'a' * 20 以内都是同一个内存地址 # 只要字符串含有非字母元素,那就不是一个内存地址 # 3.浅拷贝copy # 对于浅copy来说,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址,所以,对于第二层以及更深的层数来说,保持一致性。 l1 = [1, 2, 3, [2, 3, 4]] l2 = l1.copy() print(l1, l2) # [1, 2, 3, [2, 3, 4]] [1, 2, 3, [2, 3, 4]] print(id(l1), id(l2)) # 7625672 7623496 l1[-1].append(5) print(l1, l2) # [1, 2, 3, [2, 3, 4, 5]][1, 2, 3, [2, 3, 4, 5]] print(id(l1), id(l2)) # 7625672 7623496 print(id(l1[-1]),id(l2[-1])) # 7625160 7625160 # 4.深拷贝deepcopy() # 对于深copy来说,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变。 import copy l1 = [1, 2, 3, [2, 3, 4]] l2 = copy.deepcopy(l1) print(l1, l2) # [1, 2, 3, [2, 3, 4]] [1, 2, 3, [2, 3, 4]] print(id(l1), id(l2)) # 11506376 7625672 l1[-1].append(5) print(l1, l2) # [1, 2, 3, [2, 3, 4, 5]] [1, 2, 3, [2, 3, 4]] print(id(l1), id(l2)) # 11506376 7625672
11.编码
# Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python 3不会以任意隐式的方式混用str和bytes,
# 你不能拼接字符串和字节流,也无法在字节流里搜索字符串(反之亦然),也不能将字符串传入参数为字节流的函数(反之亦然)。 # 对于英文 s = 'laonanhai' print(s,type(s)) # laonanhai <class 'str'> s1 = b'laonanhai' print(s1,type(s1)) # b'laonanhai' <class 'bytes'> # 对于中文: s = '中国' print(s,type(s)) # 中国 <class 'str'> s1 = b'\xe4\xb8\xad\xe5\x9b\xbd' print(s1,type(s1)) # b'\xe4\xb8\xad\xe5\x9b\xbd' <class 'bytes'> # 转化 s = 'laonanhai' s2 = s.encode('utf-8') #str -->bytes encode 编码 s3 = s.encode('gbk') print(s2,s3) # b'laonanhai' b'laonanhai' s = '中国' # utf-8中文用三个字节表示一个字符 s2 = s.encode('utf-8') #str -->bytes encode 编码 # gbk中文用两个字节表示一个字符 s3 = s.encode('gbk') print(s2) # b'\xe4\xb8\xad\xe5\x9b\xbd' print(s3) # b'\xd6\xd0\xb9\xfa' ss = s2.decode('utf-8') # bytes ---> str decode 解码 print(ss) # 中国