Python常用语法 基础 安装包 1 2 3 # 以下载numpy为例 pip install numpy -i http://mirrors.aliyun.com/pypi/simple/ pip3 install torch==2.0.0+cu118 -i http://mirrors.aliyun.com/pypi/simple/
默认使pip官方的下载链接,在国外,一般使用国内的镜像网址:
1 2 3 4 https://pypi.tuna.tsinghua.edu.cn/simple/ http://mirrors.aliyun.com/pypi/simple/ http://pypi.douban.com/simple/ https://pypi.mirrors.ustc.edu.cn/simple/
pip 永久换源
1 pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
输入输出 1 2 3 4 5 >>> print ("The length of %s is %d" % (s,x)) The length of Hello is 5 >>> print ("The length of {} is {}" .format (s, x)) The length of Hello is 5
类型转换
转换
转换前
后
十转二
bin(10)
‘0b1010’
十转八
oct(9)
‘0o11’
十转十六
hex(15)
‘0xf’
转为字符串
i = 100 str(i)
‘100’
十转ASCII
chr(65)
‘A’
ASCII转十
ord(‘A’)
65
生成随机数
1 2 import randomrnd = random.randint(1 ,500 )
string 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 str1 = 'hello, world!' print (len (str1)) print (str1.capitalize()) print (str1.upper()) print (str1.find('or' )) print (str1.find('shit' )) print (str1.startswith('He' )) print (str1.startswith('hel' )) print (str1.endswith('!' )) print (str1.center(50 , '*' ))print (str1.rjust(50 , ' ' ))str2 = 'abc123456' print (str2[2 ]) print (str2[2 :5 ]) print (str2[2 :]) print (str2[2 ::2 ]) print (str2[::2 ]) print (str2[::-1 ]) print (str2[-3 :-1 ]) print (str2.isdigit()) print (str2.isalpha()) print (str2.isalnum()) str3 = ' jackfrued@126.com ' print (str3.strip())
list 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 list1 = [1 , 3 , 5 , 7 , 100 ] list2 = ['hello' ] * 5 print (len (list1))print (list1[0 ])print (list1[4 ])print (list1[-1 ])print (list1[-3 ])list1[2 ] = 300 print (list1)list1.append(200 ) list1.insert(1 , 400 ) list1 += [1000 , 2000 ] print (list1)print (len (list1))list1.remove(3 ) if 1234 in list1: list1.remove(1234 ) del list1[0 ]print (list1)list1.clear() print (list1)
列表的生成式语法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 import sysdef main (): f = [x for x in range (1 , 10 )] print (f) f = [x + y for x in 'ABCDE' for y in '1234567' ] print (f) f = [x ** 2 for x in range (1 , 1000 )] print (sys.getsizeof(f)) print (f) f = (x ** 2 for x in range (1 , 1000 )) print (sys.getsizeof(f)) print (f) for val in f: print (val)
tuple 类似cpp中结构体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 def main (): t = ('骆昊' , 38 , True , '四川成都' ) print (t) print (t[0 ]) print (t[3 ]) for member in t: print (member) t = ('王大锤' , 20 , True , '云南昆明' ) print (t) person = list (t) print (person) person[0 ] = '李小龙' person[1 ] = 25 print (person) fruits_list = ['apple' , 'banana' , 'orange' ] fruits_tuple = tuple (fruits_list) print (fruits_tuple)
dict 类似cpp中unordered_map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 def main (): scores = {'骆昊' : 95 , '白元芳' : 78 , '狄仁杰' : 82 } print (scores['骆昊' ]) print (scores['狄仁杰' ]) for elem in scores: print ('%s\t--->\t%d' % (elem, scores[elem])) scores['白元芳' ] = 65 scores['诸葛王朗' ] = 71 scores.update(冷面=67 , 方启鹤=85 ) print (scores) if '武则天' in scores: print (scores['武则天' ]) print (scores.get('武则天' )) print (scores.get('武则天' , 60 )) print (scores.popitem()) print (scores.popitem()) print (scores.pop('骆昊' , 100 )) scores.clear() print (scores)
文件读写
操作模式
具体含义
'r'
读取 (默认)
'w'
写入(会先截断之前的内容)
'x'
写入,如果文件已经存在会产生异常
'a'
追加,将内容写入到已有文件的末尾
'b'
二进制模式
't'
文本模式(默认)
'+'
更新(既可以读又可以写)
读写txt read()
1 2 3 f = open ('123.txt' , 'r' , encoding='utf-8' ) print (f.read())f.close()
如果open
函数指定的文件并不存在或者无法打开,那么将引发异常状况导致程序崩溃。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 def main (): f = None try : f = open ('123.txt' , 'r' , encoding='utf-8' ) print (f.read()) except FileNotFoundError: print ('无法打开指定的文件!' ) except LookupError: print ('指定了未知的编码!' ) except UnicodeDecodeError: print ('读取文件时解码错误!' ) finally : if f: f.close()
上面的案例使用finally语句来释放外部资源的操作;如果不愿意在finally
代码块中关闭文件对象释放资源,也可以使用上下文语法,通过with
关键字指定文件对象的上下文环境并在离开上下文环境时自动释放文件资源。
1 2 3 4 5 6 7 8 9 10 def main (): try : with open ('123.txt' , 'r' , encoding='utf-8' ) as f: print (f.read()) except FileNotFoundError: print ('无法打开指定的文件!' ) except LookupError: print ('指定了未知的编码!' ) except UnicodeDecodeError: print ('读取文件时解码错误!' )
readline()
1 2 3 4 5 6 7 8 9 10 with open ('123.txt' , mode='r' ) as f: for line in f: print (line, end='' ) time.sleep(0.5 ) print () with open ('致橡树.txt' ) as f: lines = f.readlines() print (lines)
读写csv 1 2 3 4 5 6 import csvwith open ("test.csv" , "r" ) as f: reader = csv.reader(f) for row in reader: print (row)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import csvrow = ['7' , 'hanmeimei' , '23' , '81' , '78' , '78' ] out = open ("test.csv" , "a" ) csv_writer = csv.writer(out, dialect = "excel" ) csv_writer.writerow(row) with open ('data.csv' , 'w' , newline='' ) as file: writer = csv.writer(file) writer.writerow(['姓名' , '年龄' , '性别' ]) writer.writerows(data)
读写npy 在使用numpy科学计算时,我们想保存一些矩阵和数组数据。但维度较大,有三维,四维甚至五维。此时上述方法对数据的读写就很麻烦。numpy提供了较方便保存数组和矩阵的函数.
1 2 3 4 import numpy as npx = np.array([1 ,2 ,3 ]) np.save('save' ,x) x = np.load('save.npy' )
文本格式读写 numpy还提供了文本保存格式函数savetxt,不同于二进制格式,文本文件可以直接打开查看内容 但是savetxt方法无法保存三维及以上的数组。此时可以对数组先降维,加载后再升维。
1 2 3 4 5 6 7 import numpy as npx = np.ones([1 ,2 ,3 ,4 ]) y = x.flatten() np.savetxt('save.txt' ) r = np.load('save.txt' ) x = np.reshape(r,(1 ,2 ,3 ,4 ))
读写xlsx/xls
读写json
dump
- 将Python对象按照JSON格式序列化到文件中
dumps
- 将Python对象处理成JSON格式的字符串
load
- 将文件中的JSON数据反序列化成对象
loads
- 将字符串的内容反序列化成Python对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import jsondef main (): mydict = { 'name' : '骆昊' , 'age' : 38 , 'qq' : 957658 , 'friends' : ['王大锤' , '白元芳' ], 'cars' : [ {'brand' : 'BYD' , 'max_speed' : 180 }, {'brand' : 'Audi' , 'max_speed' : 280 }, {'brand' : 'Benz' , 'max_speed' : 320 } ] } try : with open ('data.json' , 'w' , encoding='utf-8' ) as fs: json.dump(mydict, fs) except IOError as e: print (e) print ('保存数据完成!' )