为什么是python

  • 语法极简
  • 数据分析领域极度火热
  • 流行语言排名1

其他资料直接ai,metaso

4行代码,实现一万数据的正态分布显示。

1
2
3
4
import matplotlib.pyplot as plt
import numpy as np
plt.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
# 注意true 和false 是大写的关键字

None

代表 null,空

类型转化

  • bool 转化

bool(1) True

bool(0.11) True

bool(0) False

总结: 对于bool类型,凡事非0的值转为bool 都为true,0 表示false

  • 字符串转化

str() 函数

1
2
str(True)
str(3.14)
  • 数值转换
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"+1) #注意这个方法会异常
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

循环语句

  • while
1
2
3
4
a=0
while a<=10:
print('+++')
a++
  • for in

for 最常用的迭代语法,且支持多种表达式(python最强for)

1
2
3
4
5
# 与range 配置
for a in range(1,10):
print(a)


break / continue

与其他语言一直,代表循环内 跳出和跳过本次。

字符串处理

字符串格式化

占位符 描述
%d 数字占位
%f 浮点
%.f 小数部分占位
%s 字符串
%% 输出百分号
1
2
3
4
5
6
# print 中使用 % 填充变量
print("数字 %d" % 3)
print("浮点数 %f" % 3.15)
print("小数点 %.2f" % 3.34345) # 保留2位小数,如果位数不够会补0
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])# HI
print(a[:5])#默认从0开始,0可胜率
print(a[::-1])#反向输出
print(a[::2])

注意:

  1. 字符串的截取右括号为不包含,如: 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
# 将字符串的⾸字⺟变成⼤写
"china".capitalize() # China
# 将所有字符变成⼩写
"CHINA".lower() # china
# 将每个单词的⾸字⺟变成⼤写
"i have a dream".title() # I Have A Dream


# 字符串判断
"chain".startWith('c') # endWith
"chain".isdigit() # 是否数字
"chain".islower('c') # 是否全小写
"chain".find("a") # 查找字符串位置,可以当包含意义使用,-1 为不存在

"chain".index("w") # 与find类似,唯一确别,不包含的时候 不返回-1,而是抛出异常

"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']
#iterator
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))

# set1.union(set2) #并集

list(set2) # 最常用的是去重后转化为list
#iterator
for i in set2:
print(i)

# 增删改查
set2.add('a')
set2.remove(2) # 注意remove方法 如果元素不存会抛出异常,可用 discard 方法替代
set2.pop() # 弹出+remove

#集合计算
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') # str2有默认值

return , 与其他语言一样,return 关键字表示函数有返回值。

匿名函数

有时候一个函数的逻辑较简单,就可以直接声明一个匿名函数:

lambda x:x+1

匿名函数多用于在处理数据的其他函数中,传入一个处理函数,如排序,比较操作等。

面向对象

类 和 实例

1
2
3
4
5
6
7
8
9
10

class Person:
pass

#实例,注意不同于java,实例不需要 new
p1= Person()

type(p1)

isinstance(p1,Person) # 类似java中的instanceOf 方法

对象的属性和初始化

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 # 类方法 , @ 符合类似java中的注解,一般标识在方法上
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