Python 基础语法 
print("hello world!") :打印默认会换行逗号添加 end='' 解除
 
定义变量:python 定义变量不需要关键字只需要定义变量名和赋值。python 中用 # 作为注释
 
print("hello world!\n" * 3) :python 中字符串可以做乘法
 
input("请输入:") :接受键盘的输入,返回输入的字符串
 
类型转换:int(表达式) 、 str(表达式) 、 float(表达式) ,bool 值True==1 、 False==0
 
基本数据类型:str 、 int 、 float 、 bool
 
类型判断: type(表达式) 返回其类型的字符串, isinstance(表达式, 数据类型) 判断参 1 的值是否是参 2 的数据类型
 
运算符:** 乘方,// 除法(向下取整), 非 not 或 or 且and
 
if:
 
 
1 2 3 4 5 6 7 8 if  条件:    语句 elif  条件:    语句 else :    语句 
 
1 2 3 4 5 6 7 8 9 10 age = 20  match  age:    case  x if  x < 10 :          print (f'< 10 years old: {x} ' )     case  10 :          print ('10 years old.' )     case  11  | 12  | 13  | 14  | 15  | 16  | 17  | 18 :          print ('11~18 years old.' )     case  _:          print ('not sure.' ) 
 
 
1 2 3 4 5 6 7 8 9 10 msg="123" + \      +"45"  for  s in  msg:    print (s)  else :     for  i, v in  enumerate (['a' , 'b' ]):    print (i, v) 
 
for 循环常搭配 range([sta]默认0,end,[步进]) 一起使用:
1 2 3 4 5 6 7 8 9 10 11 for  s in  range (5 ):    print (s,end='' ) for  s in  range (2 ,5 ):    print (s,end='' ) for  s in  range (1 ,5 ,2 ):    print (s,end='' ) 
 
生成列表:
1 2 3 4 5 6 7 8 9 10 11 [x * x for  x in  range (1 , 3 )]  [x * x for  x in  range (1 , 3 ) if  x % 2  == 0 ]  [m + n for  m in  '12'  for  n in  '34' ]  def  foo ():    while  True :         res = yield  4          print ("res:" ,res) g = foo() print (next (g)) print (next (g)) 
 
Str(字符串) 
字符串,列表,元组,在 python 中都是序列。 
python 中字符串可以用单双三引号三种方式定义, r"str\n" 等于 "str\\n" 
 
1 2 3 4 5 6 7 8 9 str ='hi' str ="hello" str =""" hello world\n """ str =r"hello world\n"  
 
1 2 3 4 str [0 ] str [5 :] str [-10 :-1 ] str [::-1 ] 
 
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 len (str ) str .strip() str .lower() str .upper() str .swapcase() str .replace('hello' ,'hi' ) str .split('\n' ,num) print ("hello"  in  str ) print ("hello"  not  in  str ) str .capitalize() str .count("str" ) print (str .find("w" )) print (str .index("w" )) str .startswith(substr, beg, end) str .endswith(suffix, beg, end) "123abc" .isalnum() "abc" .isalpha() "123" .isdigit() lists=("1" ,"2" ,"3" ) print ("-" .join(lists)) d={"name" :"ruoxi" ,"value" :"123" } print ("+" .join(d)) 
 
字符串格式化: 因为 python 中字符串不允许与数字相加组成新的字符串 str+1 #报错 ,此时我们可借助字符串格式化来完成。 
 
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 print ("{}hello{}world" .format (1 ,"ha" ))print ("{1}hello{0}world{0}" .format (1 ,"ha" ))print ("{a}hello{b}world{a}" .format (a=1 ,b="ha" ))f'Hello {name} ' site = {"name" : "name" , "url" : "www" } print ("网站名:{name}, 地址 {url}" .format (**site))lists=['name' , 'www' ] print ("网站名:{0[0]}, 地址 {0[1]}" .format (lists))  print ('value 为: {0.value}' .format (obj))print ("{0:.2f}" .format (3.1415926 )) print ("{0:+.2f}" .format (3.1415926 )) print ("{:0>2d}" .format (3 )) print ("{0:x<4d}" .format (3 )) print ("%dhello world%s" %(12 ,1234 )) print ("%(key1)d hi world %(key2)s"  % {'key1' :12 ,'key2' :123 }) print ("%-4d"  % 5 ) print ("%+8.3f"  % 2.3 )
 
List(列表) 创建一个列表:
1 2 3 4 5 lists1=[0 ,'1' ,"2" ,[3 ,4 ,5 ]] lists2=['str' ,'hi' ] print (lists2[1 ])print (lists1)print (lists1+lists2)
 
运行结果:
1 2 3 hi [0, '1', '2', [3, 4, 5]] [0, '1', '2', [3, 4, 5], 'str', 'hi'] 
 
可以看出一个列表可接受任何类型的数据,并且两个列表之间可以向加。
常用方法:
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 lists2.append("world" )  print (len (lists2)) lists2.extend(['list' ])  lists2.insert(1 ,'hello' )  lists2.remove('str' )  lists2.pop()  lists2.pop(1 )  lists2.sort()  lists2.reverse()  lists1.count('2' )  lists1.index('2' )  lists1.index('2' ,1 ,4 )  print (lists2)print ('2'  in  lists1) list .sort() list .reverse() list .copy() lists1.clear()  del  lists1[0 ] numbers = [1 , 2 , 3 , 4 , 5 ] map (lambda  x: x**2 , numbers) filter (lambda  x: x % 2  == 0 , numbers) from  functools import  reducereduce(lambda  x, y: x * y, numbers)  
 
切片:
1 2 3 4 5 lists1[:]  lists1[:3 ]  lists1[1 :]  lists1[2 :3 ]  lists1[::-1 ]  
 
Tuple(元组) 元组和列表类似,但是不同的是元组不能修改,元组使用小括号。 元组中的元素值是不允许修改的,元组之间可相加。
1 2 3 t1=(0 ,'1' ,"2" ,[3 ,4 ,5 ]) t2=('str' ,'hi' ) print (t1+t2)
 
当元组只有一个元素时在后面添加一个 ‘,’ 才能表示它是一个元组。
1 2 3 num=(1 )  t3=(1 ,)  t4=1 ,2   
 
序列: 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 (list1,list2)=("1" ,"2" )  print (list1,list2) str ="hello" print (list ()) print (list (str )) print (tuple (str )) print (tuple (list (str ))) len (tuple (str )) print (max (list (str ))) min (str ) sum ((1 ,2 ,3 ,4 )) list (reversed (str )) print (list (enumerate (str ))) a=(1 ,2 ,3 ,4 )  b=("一" ,"二" ,"三" ) print (list (zip (a,b))) import  randomrandom.randint(1 ,10 )  random.shuffle(lst)  random.choice(seq)  random.sample(range (100 ), 10 )  
 
Set(集合) 集合是无序和无索引的集合。在 Python 中,集合用花括号编写。 可以使用 for 循环遍历 set 项目,或者使用 in 关键字查询集合中是否存在指定值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 sets={"set1" ,"set2" } set (sets) set () print (sets)for  item in  sets:     print ("iemt : " +item) print ("set2"  in  sets) a=set ('abc' )  b=set ('bcd' )  print (a - b) print (a | b) print (a & b) print (a ^ b) 
 
常用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 sets=set ("abcde" ) len (sets) print ('a'  in  sets) sets.copy()  sets.clear()  sets.add("a" )  sets.update({'b' :'2' ,'c' :'3' },'e' ,[1 ,2 ]) sets.remove("a" )  sets.discard("f" )  sets.pop()  a={1 ,2 ,3 } b={1 ,2 } a.isdisjoint(b)  a.issuperset(b)  b.issubset(a)  
 
Dictionary(字典) 键必须是唯一的,但值则不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
1 2 3 4 5 6 7 d={'a' :1 ,2 :2 ,(1 ,2 ):3 }  print (d[(1 ,2 )]) print ("a"  in  d) d["b" ]='b'   del  d['a' ] len (d) 
 
常用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 d.get("a" ,False )  d.setdefault('c' ,'c' )  d.update({'b' :'c' ,'d' :'d' })  d.pop('b' ,False )  d.popitem()  d.copy()  d.keys()  d.values()  d.items()  d.clear()  t=(1 ,2 ,3 )  d=d.fromkeys(t,'def' )  print (d) for  k, v in  d.items():     print (k, '=' , v) del  d 
 
时间 datetime: 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 from  datetime import  datetimedatetime.now()  datetime(2024 , 3 , 4 , 13 , 11 , 56 , 654634 ) datetime.now().timestamp()  datetime.fromtimestamp(t)  datetime.strptime('2015-6-1 18:19:59' , '%Y-%m-%d %H:%M:%S' ) datetime.now().strftime('%Y-%m-%d %H:%M:%S' ) datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f' )[:-3 ]  datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f' )  from  datetime import  datetime, timedelta, timezonenow = datetime.now() now + timedelta(days=2 , hours=12 )  datetime.now().astimezone(timezone(timedelta(hours=8 ))).strftime('%Y-%m-%d %H:%M:%S' ) import  pytzdatetime.now(pytz.timezone('Asia/Shanghai' )).strftime("%Y-%m-%d %H:%M:%S" ) 
 
函数 
python 中使用 def 定义函数,并且允许设置的默认值。 *变量名 允许传入任意个的值,此变量名管理一个元组。 
__name__ 当前模块的命名空间 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 def  fun (name="long" ,value="yes" ,*var ):    '函数第一行字符串作为函数的文档,通过help方法可以查看'      print (name+value)     for  s in  var:          print (s)     return  name  if  __name__ == '__main__' :    help (fun)  fun(value="ha" ,name="zhang" )  fun("1" ,"2" ,1 ,2 )  def  fun2 (*var,str ="s"  ):    for  s in  var:         print (s)     print (str ) fun2(1 ,str ="ha" )  def  person (name, *, city ):     pass  person('Jack' , city='Beijing' )  
 
函数细节:
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 def  fun ():         global  count      count=2      print ("fun() = %d" %count) count =1  fun()  print ("main() = %d" %count) def  func1 ():    x=2      def  func2 ():          nonlocal  x          x *=x         print (x)     return  func2()  func1()  def  f1 ():     return  1  f=lambda  : 1   print (f())sum  = lambda  arg1, arg2: arg1 + arg2print (sum ( 10 , 20  ))def  person (name, age, **kw ):     pass  person('Adam' , 45 , gender='M' )  extra = {'city' : 'Beijing' } person('Jack' , 24 , **extra)  
 
File(文件) 
打开文件:参 1 文件路径名,参 2 文件打开模式,参 3 编码格式(默认 win 上 gbk)
f = open("E:/test/qq.html", "r", encoding='utf-8') 
 
 
关闭文件 : f.close() 
 
模式: 
模式 
功能 
 
 
r  
只读,指针指向开头 
 
w  
只写,指针指向开头。文件不存在将创建文件 
 
a  
追加,指针指向结尾。文件不存在创建新文件 
 
可附加模式 
“+”:用于读写,”b”:以二进制打开文件 
 
常用方法: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 f = open ("E:/test/str.txt" ,"r" ,encoding='utf-8' )  print (f.closed, f.name, f.mode) f.read()  f.readline()  f.readlines()  f.write(str )  f.writelines(['第一行\n' ,'第二行' ])  f.tell()  f.seek()  f.truncate()  f.flush()  f.close()  
 
1 2 3 4 5 import  jsonperson = { "name" : "Asabeneh"  } with  open ('json_file.json' , 'w' , encoding='utf-8' ) as  f:    json.dump(person, f, ensure_ascii=False , indent=4 ) 
 
OS 模块: 常用方法:
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 import  os print (os.sep) print (os.linesep) print (os.name) print (os.curdir) os.getcwd()  os.chdir("e:" + os.sep)  os.system('cmd' )  os.stat(r'E:\test\test.txt' )  os.rename(src, dst)  os.renames(old, new)  os.listdir()  os.scandir()  os.walk()  os.mkdir(path)  os.makedirs(path)  os.remove(path)  os.rmdir(path)  os.removedirs(path)  
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import  osfile = "e:/test/test.txt"  os.path.sep  os.path.abspath("." )  os.path.basename("." )  os.path.dirname(file)  os.path.split(file)  os.path.splitext(file)  os.path.join("e:\\" ,"test" ,"test.txt" )  os.path.getatime(file)  os.path.getctime(file)  os.path.getmtime(file)  os.path.getsize(file)  os.path.exists(file)  os.path.isabs(file)  os.path.isdir(file)  os.path.isfile(file)  os.path.islink(file)  os.path.ismount(file)  
 
shutil: 1 2 3 4 5 import  shutilshutil.copy(src, dst)  shutil.copytree(src, dst)  shutil.move(src, dst)  shutil.rmtree(src)  
 
glob: 1 2 3 4 5 import  globglob.glob("*.py" )   glob.iglob("*.py" )   
 
pathlib: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 from  pathlib import  PathPath.cwd()   Path.home()   path = Path("./" )   path = path / "test.txt"    path.name   path.suffix   path.stem   path.parent   path.stat()   path.exists()   path.is_dir()   path.is_file()   path.rename("test.txt" )   path.mkdir(parents=True )   path.rmdir()   path.iterdir()   path.walk()   path.glob("*.txt" )   path.rglob("*.txt" )   
 
异常处理 1 2 3 4 5 6 7 8 9 10 11 12 try :         raise  Exception  except  OSError as  err:     print ("OS error: {0}" .format (err)) except :    print ("except" )      raise   else :    print ("else" )  finally :    print ("finally" )  
 
一些对象定义了标准的清理行为,无论系统是否成功的使用了它,一旦不需要它了,那么这个标准的清理行为就会执行。 如打开一个文件对象: 
 
1 2 3 4 with  open ("myfile.txt" ) as  f:    for  line in  f:         print (line, end="" ) 
 
1 2 3 4 5 6 7 class  MyError (Exception ):         def  __init__ (self, value ):             self.value = value         def  __str__ (self ):             return  repr (self.value) raise  MyError("my define error" ) 
 
面向对象 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class  Class (object ):     name=''       __weight=0       def  __init__ (self,name ):          Class.name="hi"           self.name=name          self.age=10      def  show (self ):          print ('name=' ,self.name,',age=' ,self.age) c=Class('world' )  c.show()  Class.name="Class"   c.name="self"   print (Class.name) 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class  Class2 (Class ):     def  __init__ (self,name ):          super ().__init__(name)      def  show (self ):          print (self.name)          @staticmethod     def  sm ():         pass           @classmethod     def  cm (cls ):         print ("cm" ) c2=Class2("Class2" ) c2.show() 
 
1 2 3 4 5 6 7 8 9 issubclass (Class2,Class) isinstance (c,Class) hasattr (Class,"name" ) hasattr (c,"name" ) getattr (Class,"name" ) setattr (Class,"name" ,"value" ) delattr (Class,"name" ) 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class  Test :    def  __init__ (self ):          self.num=1      def  __str__ (self ):          return  str (self.num)     def  __del__ (self ):          print ("实例被del" )     def  getnum (self ):         return  self.num     def  setnum (self,num ):         self.num=num     def  delnum (self ):         del  self.num     x=property (getnum,setnum,delnum)  test=Test() print (test) print (test.x) test.x=30   print (test)del  test.x del  test
 
内部作用域修改全局作用域变量需要用 global 修饰变量 
nonlocal 同理在嵌套作用域中修改内部作用域变量 
 
数据分析 numpy 安装:
 
数组创建:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import  numpy as  npdata = np.array([[1 , 2 , 3 , 4 ], [4 , 5 , 6 , 7 ]]) data = np.zeros(shape=(5 , 3 ))   data = np.ones(shape=(5 , 3 ))   data = np.empty(shape=(5 , 3 ))   data = np.arange(1 , 10 , 2 )   data = np.linspace(1 , 10 , 20 )   data = np.random.rand(3 , 4 )   data = np.random.randint(2 , 5 , size=(4 , 5 )) stacked_vertically = np.vstack((array1, array2)) stacked_horizontally = np.hstack((array1, array2)) data = data.reshape((4 , 5 ))   data.shape   data.size   data.ndim   data.dtype   
 
运算与统计:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 data = np.random.randint(2 , 5 , size=(4 , 5 )) data2 = np.random.randint(2 , 5 , size=(4 , 5 )) print (data, data + 1 )print (data + data2)arr_min = np.min (data)   arr_max = np.max (data)   arr_sum = np.sum (data)   prod = np.prod(data)   mindle = np.mean(data)   median = np.median(data)   std = np.std(data)   var = np.var(data)   data = np.array([[[1 , 2 ], [3 , 4 ]], [[5 , 6 ], [7 , 8 ]]]) print (data[0 :1 ])  print (data[0 :1 , 0 :1 ])  print (data[:, 0 :1 ])  
 
pandas 十分钟掌握 Pandas 
安装:
 
使用:
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 import  numpy as  npimport  pandas as  pds = pd.Series([1 , 2 , 3 , 5 , 6 ]) dates = pd.date_range("20130101" , periods=6 ) df = pd.DataFrame(np.random.randn(6 , 4 ), index=dates, columns=list ("ABCD" )) df2 = pd.DataFrame(     {          "A" : 1.0 ,         "B" : pd.Timestamp("20130102" ),         "C" : pd.Series(1 , index=list (range (4 )), dtype="float32" ),         "D" : np.array([3 ] * 4 , dtype="int32" ),         "E" : pd.Categorical(["test" , "train" , "test" , "train" ]),         "F" : "foo" ,     } ) df2.dtypes   df.index   df.columns   df.T   df.head()   df.tail(3 )   df.to_numpy() df.describe()   df.sort_index(axis=1 , ascending=False )   df.sort_values(by="B" )   
 
matplotlib 安装:
 
使用:
 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 from  matplotlib import  pyplot as  pltimport  randomx = range (5 ) y = lambda : [random.randint(0 , 6 ) for  i in  range (5 )] plt.figure(figsize=(20 , 8 ), dpi=80 )   plt.plot(x, y(), label="1" , color="red" , linestyle="dashed" , linewidth=2 , alpha=0.5 ) plt.plot(x, y(), label="2" ) plt.scatter(x, y())   plt.bar(x, y(), width=0.02 )   plt.barh(x, y(), height=0.02 )   plt.legend(loc="upper left" )   plt.xticks(x, ["x-"  + str (i) for  i in  x], rotation=45 ) plt.yticks(range (0 , 10 ), ["y-"  + str (i) for  i in  range (0 , 10 )]) plt.grid(alpha=0.5 )   plt.title("Title" ) plt.xlabel("xLabel" )   plt.ylabel("yLabel" )   plt.savefig("test.svg" )  plt.show()