AI之 python 基础 | 字数总计: 2.4k | 阅读时长: 10分钟 | 阅读量:
为什么是python
其他资料直接ai,metaso
4行代码,实现一万数据的正态分布显示。
1 2 3 4 import matplotlib.pyplot as pltimport numpy as npplt.hist(np.random.randn(10000 ), bins=40 ) plt.show()
安装
安装帖子多如牛毛,找资料安装即可
python2 已不建议使用
对于初学者和数据分析领域建议安装 anconda
IDE
vscode、cursor
jupyter notebook
pychem (idea同源)
主要语法 变量 变量即可变的量,在python中,可以直接定义
1 2 3 a = 100 b='zifuc' print (a)
命名规则
python 约定俗成
普通变量建议小写
不建议 字母+数字的命名方式;
驼峰写法 or 下划线写法 (统一即可)
关键字 1 2 3 4 5 6 7 False await else import pass None break except in raise True class finally is return and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield
变量赋值 1 2 3 4 5 a = 3 b=5 ,c=6 d,d = 7 ,8
变量类型 数值 数值类型主要包括 int 和float 类型。
1 2 3 4 5 a=3 b=6 display(a+b) c=3.18 print (b+c)
字符串 1 2 3 4 5 6 7 8 9 10 11 s1 = 'hello world' s2 = "this is a long \ text" s3 = """用三个双引号 分割多行文本内容"""
布尔类型 1 2 3 bool1 = True bool2 = False
None 代表 null,空
类型转化
bool(1) True
bool(0.11) True
bool(0) False
总结: 对于bool类型,凡事非0的值转为bool 都为true,0 表示false
str() 函数
1 2 3 a = int ('34' ) b = float (3 ) //float ('3.45' )
变量运算 基础运算
运算符
描述
实例
+
-
*
/
除
注意 0 不可做除数(分母)
//
整除
%
取模
**
指数
2** 相当于 2x2x2
()
括号优先级
字符串运算 字符串在某些情况下也可以使用基础运算符,如 + * 等。
1 2 3 4 print ("hello" +" world" )print ("hello" *3 )print ("str" +str (1 ))
1 2 3 hello world hellohellohello str1
赋值运算符 1 2 3 4 5 a +=1 b +=a c /= b d *=c
比较运算符
运算符
描述
举例
==
等于
100=100
>=
<
>
!=
逻辑运算符
运算符
描述
举例
and
逻辑 与
a and b
or
逻辑 或
b or c
not
取反
not a
逻辑控制 if else elif 条件判断语句,支持嵌套 可以和 逻辑运算符联合使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a = False if a: print 'true' else : pirnt 'false' b = m-n if b>0 and a: ... elif b<0 : ... else : ...
注意: 条件表达中对于,0,None 均按false 处理。非0 为true
循环语句
1 2 3 4 a=0 while a<=10 : print ('+++' ) a++
for 最常用的迭代语法,且支持多种表达式(python最强for)
1 2 3 4 5 for a in range (1 ,10 ): print (a)
break / continue 与其他语言一直,代表循环内 跳出和跳过本次。
字符串处理 字符串格式化
占位符
描述
%d
数字占位
%f
浮点
%.f
小数部分占位
%s
字符串
%%
输出百分号
1 2 3 4 5 6 print ("数字 %d" % 3 )print ("浮点数 %f" % 3.15 )print ("小数点 %.2f" % 3.34345 ) print ("这里有占位付 %s , %s" % ("我们" ,"n))
除了使用 % 来出来格式化字符串外,还可以使用format 函数专门来格式化字符串.
1 2 3 4 5 6 amount = '{:,}' .format (234234324 ) print (amount)print ('参数{},参数{},参数{}' .format (1 ,2 ,4 ))
字符串索引和下标操作 常用举例:
1 2 3 4 5 6 7 a = "CHINA" print (a[0 ])print (a[-1 ]) print (a[1 :3 ])print (a[:5 ])print (a[::-1 ])print (a[::2 ])
注意:
字符串的截取右括号为不包含,如: a[1:3] 不包含第4个char
常用字符串函数 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 " abc " .strip()"\t abc \n" .strip()"china" .upper() "china" .capitalize() "CHINA" .lower() "i have a dream" .title() "chain" .startWith('c' ) "chain" .isdigit() "chain" .islower('c' ) "chain" .find("a" ) "chain" .index("w" ) "chainnan" .count('n' ) "chain" .replace("c" ,"b" ) len ("chain" )
tuple 字符串是由一个个的字符组成的,而元祖定义了可以包含多个数据类型的序列,也都实现了字符串的大部分函数方法。
1 2 t = ('my' ,18 ,True ) t[0 :2 ]
大部分元组都由类似字符串的特征和方法。
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 l1 = list () l2 = [] l2 = ['a' ,'b' ,'c' ,'d' ,'e' ] l2.append('f' ) len (l2)l2.remove('c' ) l2.clear() del l2[0 ]l2.insert(-1 ,'sf' ) l2.pop() 弹出一个值 l2.reverse() l2.sort() l2.copy() r = [('1⽉ ' , 5610000 ), ('2⽉ ' , 4850000 ), ('3⽉ ' , 6220000 )] r.sort(reverse=True ,key=lambda x:x[1 ])
列表表达式 列表表达式是一种快捷创建list的方式,可以使用迭代代码快速生成list的元素
1 2 l3 = [i*2 for i in range (1 ,10 )] display(l3)
字典 字典,类似对象,json的数据结构。
1 2 3 4 5 6 7 d1 = {"age" :18 ,"name" :"xeon" } print (d1['age' ])d1['address' ]='北京' del d1['name' ]for k,v in d1.items(): print ("k:%s , v:%s" % (k,v))
Set集合 集合,主要特点就是不允许有重复值出现,常用在数据滤重和 交集并集计算中。 注意默认的set是无序的。
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 set1 = {"a" ,"b" ,"b" } set2 = set ([1 ,4 ,6 ,3 ,8 ]) display(set1) display(set2) display(set1.union(set2)) list (set2) for i in set2: print (i) set2.add('a' ) set2.remove(2 ) set2.pop() set1.union(set2) set1.intersection(set2) set2.issubset(set1) set2.issuperset(set1)
函数 函数即方法,在编程中无处不在。python中主要使用 def 定义函数。
1 2 3 4 def hello (str ): print ('hello %s' % str ) hello('xeon' )
如果参数过多,建议定义变量名称,强制声明变量顺序。
1 2 3 4 5 def hello2 (str1,str2='jacob' ): print ('str:' ,str1,str2) hello2(str1='xeon' ,str2='suox' ) hello2(str1='suozhi' )
return , 与其他语言一样,return 关键字表示函数有返回值。
匿名函数 有时候一个函数的逻辑较简单,就可以直接声明一个匿名函数:
lambda x:x+1
匿名函数多用于在处理数据的其他函数中,传入一个处理函数,如排序,比较操作等。
面向对象 类 和 实例 1 2 3 4 5 6 7 8 9 10 class Person : pass p1= Person() type (p1)isinstance (p1,Person)
对象的属性和初始化
1 2 3 4 5 6 7 8 9 10 11 class Person : def __init__ (self,name,age,address='北京市' ): self.name=name self.age=age self.address = address def get_info (self ): return "资料:{},{},{}" .format (self.name,self.age,self.address) p2 = Person('xeon' ,18 ,'河北廊坊' ) print (p2.get_info())
类属性和类方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 class Person : count = 0 @classmethod def incon_count (cls ): """全局类实例计数器""" cls.count+=1 def __init__ (self,name,age,address='北京市' ): """初始化构造函数""" self.name=name self.age=age self.address = address self.incon_count() def get_info (self ): """获取人员资料""" return "资料:{},{},{}" .format (self.name,self.age,self.address) p2 = Person('xeon' ,18 ,'河北廊坊' ) print (p2.get_info())
** 这里注意一点, 在使用类变量和实例变量时,必须显示的使用 cls、self 关键字开头,否则会因为变量范围而无法获取变量值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 --------------------------------------------------------------------------- UnboundLocalError Traceback (most recent call last) Cell In[274 ], line 18 15 def get_info (self ): 16 return "资料:{},{},{}" .format (self.name,self.age,self.address) ---> 18 p2 = Person('xeon' ,18 ,'河北廊坊' ) 19 print (p2.get_info()) Cell In[274 ], line 13 , in Person.__init__(self, name, age, address) 11 self.age=age 12 self.address = address ---> 13 self.incon_count() Cell In[274 ], line 7 , in Person.incon_count(cls) 5 @classmethod 6 def incon_count (cls ): ----> 7 count+=1
一切皆对象 在py中,一切都可以是对象,包括一个数字,一个字符串,甚至是函数本身、甚至class本身。
1 2 3 4 5 dir () dir (Person)help (p2)
注释 py中使用三个 双引号包含的文字默认为代码的api 注释和文档
1 2 3 4 5 6 7 8 9 class Cart : """购物车对象""" def cart_info (self ): """获取购物车信息""" pass