Day2 python基础2
一、模块
python中提供强大的标准库和第三方库。
sys
1 import sys 2 3 print(sys.path) #打印环境变量 4 5 print(sys.argv) #打印相对路径,但在pycharm中调用绝对路径,所以再pycharm中打印绝对路径
os
1 import os 2 3 cmd_res = os.system("dir") #os.system直接输出到屏幕上,输出之后就没了,不保存结果 4 print(cmd_res) #输出0,只是代表命令执行成功 5 6 cmd_res = os.popen("dir").read() #通过read()从内存中取回 7 print(cmd_res) 8 9 os.mkdir("new_dir") #创建一个新目录
自己写的abc.py模块只能在当前目录下导入,若想在系统的任何地方都使用,可把abc.py模块放到python全局环境变量目录中的site-packages下,可用print(sys.path)查看python环境变量列表。
二、pyc
python可以看作是一种先编译后解释的语言。
python程序在运行时,先查看有无对应的pyc文件,比较其生成时间与源代码修改时间,若生成pyc文件后源代码未修改过,直接载入pyc文件;若源代码已经修改过或python程序是第一次运行,找不到其pyc文件,则先进行编译,然后进行解释,python解释器将编译结果写回到pyc文件中。
三、数据类型
1.数字
python3中支持三种不同的数字类型:
整型(int):取值范围与具体机器有关。
浮点型(float)包括整数部分和小数部分,可采用科学计数法,如2.5E-2==2.5*10^-2
复数(complex)包括实数部分和虚数部分,可用a+bj,或complex(a,b)表示,其中a,b均为浮点型。
2.布尔值
真或假
1 或 0
3.字符串
利用 + 号拼接字符串,每出现一次就在内存中重新开辟一块空间,故不推荐。
具体拼接方法见http://www.cnblogs.com/zhangwb204/p/8179146.html中第四点,输入。
字符串常用方法
1 >>> name = "zhang is me" 2 >>> name[2:] #分片 3 'ang is me' 4 >>> name.capitalize() #首字母大写 5 'Zhang is me' 6 >>> name.count("a") #字符统计 7 1 8 >>> name.center(50,"-") 9 '-------------------zhang is me--------------------' 10 >>> name.endswith("me") #是否以特定字符结尾 11 True 12 >>> name.find('i') #字符串中第一个特定字符的位置 13 6 14 >>> name.isalnum() #判断是否仅包含英文字符和数字 15 False 16 >>> name.isalpha() #判断是否仅包含英文字符 17 False 18 >>> name.isdecimal() #判断是否仅包含十进制数 19 False 20 >>> '123'.isdigit() #判断是否仅包含整数 21 True 22 >>> '5a'.isidentifier() #判断是否是合法的标识符 23 False 24 >>> '5_a'.islower() #判断字符串中字母是否是小写 25 True 26 >>> '233.3'.isnumeric() #判断字符串中是否仅有数字 27 False 28 >>> 'My Name Is Z'.istitle() #判断是否是标题 29 True 30 >>> 'My Name Is Z'.isprintable() #判断是否可打印,一般tty file,drive file不可打印 31 True 32 >>> '5Aa'.isupper() #判断字符串中字母是否是大写 33 False
1 >>> '+'.join(['1','2','3']) 2 '1+2+3' 3 >>> name.ljust(50,'-') #输出长度为50,并使字符串居左显示,其余位置用 - 填充 4 'zhang is me---------------------------------------' 5 >>> name.rjust(50,'*') 6 '***************************************zhang is me' 7 >>> name.center(50,'@') 8 '@@@@@@@@@@@@@@@@@@@zhang is me@@@@@@@@@@@@@@@@@@@@' 9 10 >>> 'zHAng'.lower() #字符串中字母都变为小写 11 'zhang' 12 >>> 'zHAng'.upper() #字符串中字母都变为大写 13 'ZHANG' 14 15 >>> '\nzhang\n'.lstrip() #去除字符串左空格或换行 16 'zhang\n' 17 >>> '\nzhang\n'.rstrip() #去除字符串右空格或换行 18 '\nzhang' 19 >>> ' zhang\n'.strip() #去除字符串两侧空格或换行 20 'zhang' 21 22 >>> p = str.maketrans("abcdef","123456") #匹配替换 23 >>> 'zhang'.translate(p) 24 'zh1ng' 25 26 >>> 'zhang zz'.replace('z','Z',2) #将z替换为Z,替换前两个 27 'Zhang Zz' 28 29 >>> 'zhang zz'.rfind('z') #从左往右,找到最右边的z的位置 30 7 31 32 >>> 'zhang zz'.split('z') #按某一字符分割字符串为列表 33 ['', 'hang ', '', ''] 34 35 >>> 'zhang zz\nrr'.splitlines() #按换行符分割字符串为列表 36 ['zhang zz', 'rr'] 37 38 >>> 'zhangWB'.swapcase() #字母大小写交换 39 'ZHANGwb' 40 41 >>> 'zhangWB'.title() 42 'Zhangwb' 43 44 >>> 'zhangWB'.zfill(50) 45 '0000000000000000000000000000000000000000000zhangWB'
1 >>> name2 = "my name is {name} and i am {year} years old" 2 >>> name2.format(name="zhang",year=18) 3 'my name is zhang and i am 18 years old' 4 >>> name2.format_map({'name':'zhang','year':18}) #利用字典 5 'my name is zhang and i am 18 years old'
python3中对文本和二进制数据类型作了更清晰的区分。文本总为Unicode,为str类型,二进制数据为bytes类型。
1 msg="我爱北京天安门" 2 print(msg) 3 print(msg.encode(encoding = "utf-8")) 4 print(msg.encode(encoding = "utf-8").decode(encoding="utf-8"))
输出:
我爱北京天安门 b'\xe6\x88\x91\xe7\x88\xb1\xe5\x8c\x97\xe4\xba\xac\xe5\xa4\xa9\xe5\xae\x89\xe9\x97\xa8' 我爱北京天安门
4.列表
列表采用 [ ] 标识 。
创建列表:
1 list = ['one','two',3,4,5.0]
切片:
1 list = ['one','two',3,4,5.0] 2 print(list) 3 print(list[0]) #从左到右索引默认从0开始 4 print(list[-1]) #从右到左索引默认从-1开始 5 print(list[0:3]) #顾头不顾尾 6 print(list[:4]) #输出从0开始到3的所有元素 7 print(list[0:]) #输出从0开始的所有元素 8 print(list[-3:-1]) #输出从-3开始到-2的所有元素 9 print(list[-4:]) #输出从-4开始到-1的所有元素 10 print(list[0::2]) #跳着切
输出结果:
['one', 'two', 3, 4, 5.0] one 5.0 ['one', 'two', 3] ['one', 'two', 3, 4] ['one', 'two', 3, 4, 5.0] [3, 4] ['two', 3, 4, 5.0] ['one', 3, 5.0]
增:
1 list = ['one','two','two','three','four','five','six','seven'] 2 print(list) 3 list.append('six') #在列表尾追加一个元素 4 print(list) 5 list.insert(1,'new_two') #在列表指定位置插入一个元素 6 print(list) 7 list2 = [1,2,3] 8 list.extend(list2) #合并两张列表 9 print(list,list2)
输出结果:
['one', 'two', 'two', 'three', 'four', 'five', 'six', 'seven'] ['one', 'two', 'two', 'three', 'four', 'five', 'six', 'seven', 'six'] ['one', 'new_two', 'two', 'two', 'three', 'four', 'five', 'six', 'seven', 'six'] ['one', 'new_two', 'two', 'two', 'three', 'four', 'five', 'six', 'seven', 'six', 1, 2, 3] [1, 2, 3]
#copy的使用 import copy num = ['one','two','three',[1,2],'four'] num2 = num.copy() #浅copy,可理解为只copy第一层,之后的直接copy地址 #浅copy,还可写为num3 = num[:]或num3 = list(num)或list3 = copy.copy(list) num3 = copy.deepcopy(num) #深copy,完全独立的克隆一份列表 print(num) print(num2) print(num3) print() num[1]=2 num[3][1]=5 #第一层不变,第二层变 print(num) print(num2) print(num3)
输出结果:
['one', 'two', 'three', [1, 2], 'four'] ['one', 'two', 'three', [1, 2], 'four'] ['one', 'two', 'three', [1, 2], 'four'] ['one', 2, 'three', [1, 5], 'four'] ['one', 'two', 'three', [1, 5], 'four'] ['one', 'two', 'three', [1, 2], 'four']
删:
1 list = ['one','two',3,4,5.0,6,7] 2 print(list) 3 del list[2] #按位置删除 4 print(list) 5 list.pop() #默认删除最后一个元素 6 print(list) 7 list.pop(3) #按位置删除 8 print(list) 9 list.remove('two') #按元素删除 10 print(list) 11 list.clear() #清空列表 12 print(list)
输出结果:
['one', 'two', 3, 4, 5.0, 6, 7] ['one', 'two', 4, 5.0, 6, 7] ['one', 'two', 4, 5.0, 6] ['one', 'two', 4, 6] ['one', 4, 6] []
改:
1 list = ['one','two',3,4,5.0,6,7] 2 print(list) 3 list[1]='new two' 4 print(list)
输出结果:
['one', 'two', 3, 4, 5.0, 6, 7] ['one', 'new two', 3, 4, 5.0, 6, 7]
查:
1 list = ['one','two','two','three','four'] 2 print(list) 3 print(len(list)) #输出列表长度 4 print(list.index('two')) #输出第一个所找元素的下标 5 print(list.count('two')) #输出列表中某元素的个数 6 list.reverse() #反转 7 print(list) 8 list.sort() #按ASCII码排序 9 print(list) 10 list = ['one','two','two','three','four'] 11 for i in list: #循环 12 print(i)
输出结果:
['one', 'two', 'two', 'three', 'four'] 5 1 2 ['four', 'three', 'two', 'two', 'one'] ['four', 'one', 'three', 'two', 'two'] one two two three four
5.元组
元组和列表差不多,只是一旦创建就不能修改,又叫只读列表。
创建元组
1 num = ('one','two','three')
只有两个方法count和index。
6.字典
dictionary是{key:value}的数据类型。字典中的数据是无序的,且key唯一。
用法:
创建字典:
1 info = { 2 'stu1101':"Zhang San", 3 'stu1102':"Li Si", 4 'stu1103': "Wang Wu" 5 }
查:
>>> info = { 'stu1101':"Zhang San", 'stu1102':"Li Si", 'stu1103': "Wang Wu" } >>> print(info) #dictionary是无顺序的 {'stu1101': 'Zhang San', 'stu1102': 'Li Si', 'stu1103': 'Wang Wu'} >>> print(info['stu1101']) Zhang San >>> print(info.get('stu1101')) Zhang San >>> print(info.get('stu1104')) None >>> print('stu1102' in info) True
>>> info = { 'stu1101':"Zhang San", 'stu1102':"Li Si", 'stu1103': "Wang Wu" } >>> print(info.values()) dict_values(['Zhang San', 'Li Si', 'Wang Wu']) >>> print(info.keys()) dict_keys(['stu1101', 'stu1102', 'stu1103']) >>>
改:
info['stu1101'] = "张三" >>> print(info) {'stu1101': '张三', 'stu1102': 'Li Si', 'stu1103': 'Wang Wu'}
增:
>>> info['stu1104'] = "Zhao Liu" >>> print(info) {'stu1101': '张三', 'stu1102': 'Li Si', 'stu1103': 'Wang Wu', 'stu1104': 'Zhao Liu'}
删:
>>> del info['stu1101'] >>> print(info) {'stu1102': 'Li Si', 'stu1103': 'Wang Wu', 'stu1104': 'Zhao Liu'} >>> info.pop('stu1102') 'Li Si' >>> print(info) {'stu1103': 'Wang Wu', 'stu1104': 'Zhao Liu'} >>> info.popitem() #任意删除一个 ('stu1104', 'Zhao Liu') >>> print(info) {'stu1103': 'Wang Wu'}
其他:
#update >>> info = { 'stu1101':"Zhang San", 'stu1102':"Li Si", 'stu1103': "Wang Wu" } >>> info2 = { 'stu1101':"new Zhang San", 1:2, 3:4 } >>> info.update(info2) #若存在则替换,不存在则添加 >>> print(info) {'stu1101': 'new Zhang San', 'stu1102': 'Li Si', 'stu1103': 'Wang Wu', 1: 2, 3: 4}
#items 将字典转换为列表,列表元素为key和value组成的元组 >>> print(info.items()) dict_items([('stu1101', 'new Zhang San'), ('stu1102', 'Li Si'), ('stu1103', 'Wang Wu'), (1, 2), (3, 4)])
#fromkeys 通过一个列表生成默认字典 >>> info3 = dict.fromkeys([6,7,8],[1,{"name":"zhang"},444]) >>> print(info3) {6: [1, {'name': 'zhang'}, 444], 7: [1, {'name': 'zhang'}, 444], 8: [1, {'name': 'zhang'}, 444]} >>> info3[7][1]['name'] = "li" #修改其中一个key对应的value,所有的value都变 >>> print(info3) {6: [1, {'name': 'li'}, 444], 7: [1, {'name': 'li'}, 444], 8: [1, {'name': 'li'}, 444]}
#setdefault 若key所对应value已存在,则返回原value,否则返回新value,并加入字典 >>> print(info.setdefault('stu1101',"new Zhang San")) Zhang San >>> print(info) {'stu1101': 'Zhang San', 'stu1102': 'Li Si', 'stu1103': 'Wang Wu'} >>> print(info.setdefault('stu1104',"new Zhang San")) new Zhang San >>> print(info) {'stu1101': 'Zhang San', 'stu1102': 'Li Si', 'stu1103': 'Wang Wu', 'stu1104': 'new Zhang San'}
#循环 >>> for i in info: #仅输出key print(i) stu1101 stu1102 stu1103 stu1104 >>> for i in info: print(i,info[i]) stu1101 Zhang San stu1102 Li Si stu1103 Wang Wu stu1104 new Zhang San >>> for k,v in info.items(): #结果同上,但效率低 print(k,v) stu1101 Zhang San stu1102 Li Si stu1103 Wang Wu stu1104 new Zhang San
7.集合
集合是无序的,不重复的
常用操作
>>> list_1 = [32,4,5,6,6,7,8,7] >>> print(list_1) [32, 4, 5, 6, 6, 7, 8, 7] >>> set_1 = set(list_1) #创建 >>> print(set_1) {32, 4, 5, 6, 7, 8} >>> set_2 = set([4,5,876,3,1]) >>> print(set_1,set_2) {32, 4, 5, 6, 7, 8} {1, 3, 4, 5, 876} >>> #交集 >>> set_1.intersection(set_2) {4, 5} >>> set_1 & set_2 {4, 5} >>> #并集 >>> set_1.union(set_2) {32, 1, 3, 4, 5, 6, 7, 8, 876} >>> set_1 | set_2 {32, 1, 3, 4, 5, 6, 7, 8, 876} >>> #差集 >>> set_1.difference(set_2) {32, 8, 6, 7} >>> set_1 - set_2 {32, 8, 6, 7} >>> #对称差集 >>> set_1.symmetric_difference(set_2) {32, 1, 3, 6, 7, 8, 876} >>> set_1 ^ set_2 {32, 1, 3, 6, 7, 8, 876} >>> #子集,父集 >>> set_3 = set([5,6]) >>> set_3.issubset(set_1) True >>> set_3.issubset(set_2) False >>> set_1.issuperset(set_2) False >>> set_1.issuperset(set_3) True >>> #添加 >>> set_1.add(233) >>> print(set_1) {32, 4, 5, 6, 7, 8, 233} >>> set_1.update([333,666,777]) >>> print(set_1) {32, 4, 5, 6, 7, 8, 233, 777, 333, 666} >>> #删除 >>> set_1.remove(333) >>> print(set_1) {32, 4, 5, 6, 7, 8, 233, 777, 666} >>> set_1.remove(999) #元素不存在时报错 Traceback (most recent call last): File "<pyshell#37>", line 1, in <module> set_1.remove(999) KeyError: 999 >>> set_1.discard(233) >>> print(set_1) {32, 4, 5, 6, 7, 8, 777, 666} >>> set_1.discard(999) #元素不存在时不报错 >>> print(set_1) {32, 4, 5, 6, 7, 8, 777, 666} >>> set_1.pop() 32 >>> print(set_1) {4, 5, 6, 7, 8, 777, 666} #判断某元素在不在集合中 >>> 4 in set_1 True >>> 4 not in set_1 False

浙公网安备 33010602011771号