python初学习

python初学知识,内容主要整合了慕课网的课程知识,一个很棒的学习网站

一、基础

1. 基础数据类型

  • 整数
    • 二进制:0b开头
    • 十六进制:0x开头
  • 浮点
  • 字符串: “ABC”、’ABC’
    • 单字符转义:\
    • 单个字符串(行)转义,表示一个raw字符串,里面的字符不用转义:r’ xxxxx ‘ (不包括’’,””)
    • 多行转义:’’’ xxxxxx ‘’’
    • 多行单个字符串(raw字符串): r’’’ xxxxxxx ‘’’
  • 布尔:True、False
    • 运算:and、or、not(优先级最高)
  • 空值:None

2. 变量

  • 弱类型,根据赋值决定变量的类型

3. 字符串方法

  • format:{ } 替换输出

    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
    # 字符串模板
    template = 'Hello {}'
    # 模板数据内容
    world = 'World'
    result = template.format(world)
    print(result) # ==> Hello World

    # 指定顺序
    template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.'
    result = template.format('World', 'China', 'Beijing', 'imooc')
    print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
    # 调整顺序
    template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.'
    result = template.format('World', 'China', 'Beijing', 'imooc')
    print(result) # ==> Hello imooc, Hello Beijing, Hello China, Hello World.

    # 指定{}的名字w,c,b,i
    template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.'
    world = 'World'
    china = 'China'
    beijing = 'Beijing'
    imooc = 'imooc'
    # 指定名字对应的模板数据内容
    result = template.format(w = world, c = china, b = beijing, i = imooc)
    print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc.
  • 分割

    • 索引取值,类似java的字符串数组
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    s = 'ABC'
    a = s[0] # 第一个
    b = s[1] # 第二个
    c = s[2] # 第三个
    print(a) # ==> A
    print(b) # ==> B
    print(c) # ==> C

    # 取子串,不包括endIndex
    a = s[startIndex:endIndex]

    [1:]--获取从位置1开始后面的字符(默认首位是0

    [:-1]--删除位置为-1的字符(也就是获取从位置0带位置-1之间的字符)

    [-1:]--获取位置-1的字符

    [::-1]--从最后一个元素到第一个元素复制一遍。(也就是倒序)

    [:]--相当于完整复制一份str
    • [1:]、[:-1]和[::-1]详解 :参考

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      索引从前往后为0、1、2...,从后往前 -1、-2、...
      [1:]--获取从位置1开始后面的字符(默认首位是0)

      [:-1]--删除位置为-1的字符

      [-1:]--获取位置-1的字符

      [::-1]--倒序(从最后一个元素到第一个元素复制一遍)

      [:]--完整复制一份str

4. 条件

  • if

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    if 条件:
    逻辑
    else:
    逻辑

    # 注意逻辑代码是要缩进的,4个空格

    score = 59
    if score < 60:
    print('抱歉,考试不及格')
    else:
    if score >= 90:
    print('恭喜你,拿到卓越的成绩')
    else:
    # elif = else if
    if score < 60:
    print('抱歉,考试不及格')
    elif score >= 90:
    print('恭喜你,拿到卓越的成绩')

5. 循环

  • for

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    for i in arr:
    逻辑

    # 嵌套循环
    s1 = 'ABC'
    s2 = '123'
    s3 = 'xyz'
    for i in s1:
    for j in s2:
    for k in s3:
    print(i + j + k)
  • while

    1
    2
    while True:
    逻辑
  • break:提前终止循环

  • continue:提前继续循环

6. 容器

6.1 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
28
29
30
31
32
33
34
35
36
37
38
39
40
sources = [12,23,34]
list2 = [23,'lebron',44,55]
num = 0
for item in list2:
print(item)
num = num +1
if num % 2 == 0:
print(item)

# 取子列表
subList = list2[0:3]

# 倒序
print(list2[-1]) # 55
print(list2[-2]) # 44

# 添加新元素
sources.append(44)
# index插入的位置,value 插入的值
index = 0
value = 11
sources.insert(index,value)

# 删除
sources.pop()
firstValue = sources.pop(0)

# 替换
sources[1] = 'James'

# 多维数组
l1 = [11,22,33]
l2 = [44,55,66]
l = [l1,l2]
print(l[1,0]) # ==> 44
for item in l:
a = item[0]
b = item[1]
c = item[2]
print(a*b*c)
6.2 tuple:元组
  • 有序
  • 基础数据类型(数字、布尔、字符)固定不变,不可添加(性能>>list)
  • 组合类型可变,原因为指向同一个地址
  • 可与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
t = ('Alice','Bob','Candy')
print(t[0:2])
l = list(t)
L = ['David','Ellena']
t2 = tuple(L)

one = (1)
print(one) # ==> 1 ,因为(1)被解释结果为1
one2 = (1,)
print(one2) # ==> (1,)

# 嵌套
T = ((1+2), ((1+2),), ('a'+'b'), (1, ), (1,2,3,4,5))
print(T) ==> 3 个tuple (3, (3,), 'ab', (1,), (1, 2, 3, 4, 5))

# 可变情况
T = (1, 'CH', [3, 4])
L = T[2]
print(L) # ==> [3, 4]
# 尝试替换L中的元素
L[1] = 40
print(L) # ==> [3, 40]
print(T) # ==> (1, 'CH', [3, 40])
# 直接替换tuple中的list会报错
L2 = [3, 40]
# 尝试替换tuple中的list
T[2] = L2 # ==> 报错
  • 方法
    • count:统计元素次数
      • index:返回指定元素的下标(注:元素不存在会报错)
6.3 dict:字典
  • 键值对映射
  • 查找速度快 > list
  • 占用内存大 < list
  • 无序(3.5版本)、有序(3.6、3.7)
  • key不可变(tuple可以作key,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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
d = dict() # ==> {} 空
d = {
'Alice':50,
'Bob':60
}
print(d)
print(d['Bob']) # ==> 60

# 取值
if 'Alice' in d:
print(d['Alice']) # 不判空,无key时会报错
# 使用get方法,key空不会报错
print(d.get('Ed')) # ==> None

# 添加:无key新增,有key更新值
d1 = dict()
d1['Mini'] = 73
d1['Coco'] = 80
# 值可以为任意类型
d2 = dict()
d2['Mini'] = [72,73]
d2['Mini'].append(74)
print(d2) # ==> { 'Mini': [72,73,74]}

# 删除
d3 = {
'Alice':60,
'Bob':20
}
alice = d.pop('Alice') # 注意:key不存在会报错
print(alice) # ==> 60
print(d) # ==> { 'Bob': 20 }
# 返回所有key,list类型
d3['Coco'] = 60
keys = d3.keys() # ==> [ 'Coco','Bob']

# tuple作为key
d = dict()
key = (1, 2, 3)
d[key] = True
print(d) # ==> { (1,2,3): True }

# 遍历
d4 = {
'Alice':20,
'Bob':30,
'Coco':40
}
for key in d4:
value = d4[key]
print(value)

for key,value in d4.items():
print(key,value)

for key in d4.keys():
print(key)
for value in d4.values():
print(value)
  • 方法
    • keys:返回所有key,list类型
    • values:返回所有value,list类型
    • items:返回所有值,包含key和value
    • clear:清除所有元素
6.4 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
26
27
28
29
30
31
32
33
34
35
36
# 创建
s = set([1,2,3])
print(s) # ==> set([1,3,2])

# 判断是否存在
1 in s # ==> True

# 添加
names = ['Alice','Bob']
s1 = set(names)
s1.add('Coco')
# 批量添加
names2 = ['David','Linda']
s1.update(names)

# 删除
s2 = set(['Alice','Bob','Coco'])
s2.remove('Alice')
print(s2) # ==> set(['Bob','Coco'])
s2.remove('Tina') # 报错

# 删除
s3 = set(['Alice','Bob'])
s3.discard('Alice')
s3.discard('Coco')

# 清除
s4 = set(['Alice','Bob'])
s4.clear() # ==> set([])

# 子集/超集、重合
s5 = set(['Alice','Bob'])
s6 = set(['Alice','Bob','Coco'])
s5.issubset(s6) # True
s6.issuperset(s5) # True
s5.isdisjoint(s6) # False 有重合,True 无重合
  • 方法
    • add:添加
    • remove:删除(元素不存在报错)
    • discard:删除(元素不存在不会报错)
    • clear:清除所有元素
    • issubset:是否子集
    • issuperset:是否超集
    • isdisjoint:是否重合,有重合False、无重合True

7.函数

  • 引入后,直接调用即可
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 定义
def 函数名(参数):
函数体

def abs(param):
if param < 0:
return -param
else:
return param # 无返回则输出为 None
# 返回多个值使用 ,(逗号)分隔
def square(side):
perimeter = 4*side
area = side*side
return perimeter,area
p,a = square(5) # p=20,a=25
result = square(5) # ==> (20,25)

# 参数可为任意类型
# 判断参数类型
isinstance(100,int) # ==> True
isinstance('23',str) # ==> True

# 默认参数,在必须的参数后面
def power(x,n):
s = 1
while n >0:
n = n-1
s = s*x
return s

def power(x,n=2):
s = 1
while n > 0:
n = n-1
s = s*x
return s
power(3,4) # ==> 3 x 3 x 3 x 3
power(3) # ==> 3 x 3

# 可变参数,任意个数,参数类型实际为tuple * 必要
def averages(*args):
for i in args:
print(i)
print(args)
averages(1,2,3) # ==> 1,2,3 (1,2,3)

# 可变关键字参数,给参数定义key,固定参数名,参数类型实际为dict ** 必要
def info(**kwargs):
gender = kwargs.get('gender')
name = kwargs.get('name')
info(gender = 'girl', name = 'Coco')

# 对于一个拥有必需参数,默认参数,可变参数,可变关键字参数的函数,定义顺序如下
def func(param1, param2, param3 = None, *args, **kwargs):
print(param1)
  • 方法
    • isinstance:判断参数类型

二、面向对象

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 定义:三种方式
class Person: pass # pass为空语句,只是为了保持程序结构的完整性
class Person(): pass
class Person(object): pass

# 类属性定义
class Animal(object):
location = 'Asia' # 所有实例均会拥有,只有一份,如果一个实例改了,则同步所有实例
def __init__(self,name,age):
self.name = name
self.age = age

dog = Animal('wang',23)
cat = Animal('miao',12)
print(Animal.location) # ==> Asia
Animal.location = 'Africa'
print(Animal.location) # ==> Africa
dog.location = 'Cn'
print(dog.location) # ==> Cn ,相当于加了个实例属性
print(Animal.location) # ==> Africa

# 类方法定义:@classmethod
class Animal(object):
__location = 'Asia'
def __init__(self):
pass
@classmethod
def set_location(cls,location): # 第一个参数代表类自身
cls.__location = location

# 实例:类名+()
mango = Person()
cheng = Person()
# 实例属性的定义
mango.age = 23
mango.sex = 'girl'
print(mango.age) # ==> 23

# 属性的初始化,创建实例会自动调用:__init__()
class Person(object):
def __init__(self, name, sex, age): # 第一个参数必须为self(代表自身,名称可变)
self.name = name
self.sex = sex
self.age = age

person = Person('mango','girl',23)

# 实例属性的优先级 > 类属性,实例属性无法修改类属性

# 访问限制
# 私有属性(只能在类内部使用):__开头
class Animal(object):
__location = 'Asia'
print(Animal.__location) # ==> 报错

class Animal(object):
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name
dog = Animal('Alice')
print(dog.__name) # ==> 报错

# 实例方法:第一个参数同样为 self,引用,指向实例对象本身
class Person(object):
def __init__(self,name):
self.__name = name
def get_name(self):
return self.__name
p = Person('Alice')
print(p.get_name()) # ==> Alice

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 定义继承:(要继承的类)
class Person(object):
def __init__(self,name):
pass
class Student(Person):
def __init__(self,name,gender):
super(Student,self).__init__(name) # 初始化从父类继承而来的属性
self.gender = gender
person = Person('mango')
student = Student('mango','girl')

# 多态:子类调用方法时会覆盖父类方法,否则顺着继承链调用父类方法

# 多重继承
class children(Teacher,Student):
pass

# 判断类型:isinstance
isinstance(person,Person) # ==> True
isinstance(person,Student) # ==> False
isinstance(student,Person) # ==> True
isinstance(student,Student) # ==> True
# 获取变量的类型:type
type(person)

# 获取变量的所有属性,返回的是字符串列表:dir

# 获取/设置指定的属性:getattr
getattr(person,'name') # ==> mango
setattr(person,'name','cheng')

# 设置可变参数实例
class Person(object):
def __init__(self,name,gender,**kwargs):
self.name = name
self.gender = gender
for k,v in kwargs.items():
setattr(self,k,v)

p = Person('mango','girl',age = 23,height = 188)
print(p.name) # ==> mango
print(p.age) # ==> 23
print(p.height) # ==> 188

3.类的特殊方法

  • 双下划线开头
  • 双下划线结束
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# __str__:转化为字符串
num = 23
str(num) # ==> '23'
# __repr__:转化为字符串,显示给开发人员看的,返回的是地址
class Student(object):
def __init__(self,name):
self.name = name
def __str__(self):
return('name={}'.format(self.name))
def __repr__(self):
return('repr name={}'.format(self.name))
s = Student('mango')
print(str(s)) # ==> name=mango
print(repr(s)) # ==> repr name=mango

# __len__:tuple/list的元素个数,如果是对象,需要重写该方法

# 数学运算:加减乘除
# 加法:两个分数a/b和c/d相加等于(a*d+b*c)/b*d,r.p、r.q就相等于前面的c和d
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)

def __str__(self):
return '{}/{}'.format(self.p, self.q)

# 减法 44





# __slots__:限制随意添加属性
class Student(object):
__slots__ = ('name','age') # 限定只有这两个属性
def __init__(self,name,age):
self.name = name
self.age = age
s = Student('mango',23)
s.gender = 'girl' # 报错

# __call__:把类实例变成一个可调用对象
class Fib(object):
# fib = []
def __init__(self,num):
self.fib = []
for i in range(num):
self.fib.append(i) # 随便添加,并非真的是斐波那契数列,下个例子才是
# print(self.fib)
def __call__(self,fib):
# print(self.fib)
return self.fib

f = Fib(5)
print(f(5)) # ==> [0,1,2,3,4,5]

class Fib(object):
def __init__(self):
self.res = []

def __call__(self, num):
a = 0
b = 1
for x in range(num):
self.res.append(a)
a, b = b, a + b # 斐波那契数列
return self.res

f = Fib()
print(f(10))

4.模块和包

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
# main.py 自身的模块
import tools # 导入的模块
from network import tools # 导入network包的tools.py模块

# 定义模块
# tools.py # 创建一个tools.py文件,在此实现函数功能

# 导入模块
# 导入整个模块:使用时需要带上模块名
import math
math.pi
math.pow(2,3)
# 指定导入模块:使用不需要带上模块名
from math import pi
from math import * # 全部
pi
# 重命名导入模块:解决相同函数冲突问题
from math import pow as mathpow

# 模块导入的路径:官方模块不需要考虑
import sys
print(sys.path) # 该模块路径 ==> [ '','D:/xxxx/',.. ] 第一个空代表当前路径
l = sys.path
l.insert(1,'../') # 增加解析当前路径的上一级目录
print(sys.path)

# 安装/卸载第三方模块:pip
pip install django
pip uninstall django

5.输入输出

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
38
39
40
41
42
# input:程序输入,输入的为字符串
# import os
num = input('input number:')
num = int(num)

# open:打开文件(路径,打开模式)
f = open('text.txt','r') # 当前路径下的text,打开模式为只读模式
f.close
# 打开二进制文件:图片、视频、压缩文件等
f2 = open('test.jpg','rb') # rb 二进制格式只读模式

# 读取内容
# read:读取若干字符
s = f.read(5)
# readline:读取一行,最多返回一行结果
s = f.readline(20)
# readlines:读取多行,包含换行符;最大为缓冲区大小
s = f.readlines()
# 迭代器方式读取
iter_f = iter(f)
for line in iter_f:
print(line)

# 写入内容
# write:写入若干字符
f = open('temp.txt','w') # 写模式
f.write('hello')
f.close()
# writelines:写入若干行
lines = ['hello\n','mango\n’,‘cheng\n'] # 三行
f.writelines(lines) # 清空文件内容,重新写入
f.close() # 把剩下缓冲区内容全部同步到磁盘(单次写入最多到缓冲区大小)
# 通过不同的模式,指定写入的方式
f = open('test.txt','a') # 尾部追加
f = open('text.txt','a+') # 尾部追加,读写
f.readlines() # ==> [] ,因为游标在尾部
# 指针游标操作 seek(offset[,whence]) 偏移量,偏移相对位置;0--文件首部、1--当前位置、2--文件尾部
f.seek(-3,2) # 移动文件的游标位置:在末尾的位置往前偏移3个字节
f.readlines() # ==> 全部内容
# 正确关闭文件:with ,close 如果在前面的语句发生异常,可能会不执行
with open('test.txt','r') as f:
pass # 不需要显示调用close
  • 文件打开方式

    mode 说明 注意
    r 只读 文件必须存在
    w 只写 文件不存在则创建,存在则清空
    a 追加 文件不存在则创建
    r+/w+ 读写
    a+ 追加和读写
    rb/wb/ab/rb+/wb+/ab+ 二进制

6.网络编程

服务端:新增Socket、绑定ip和端口、监听连接、接受连接

客户端:新增Socket、连接服务端

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
# Socket
# server.py
import socket
server = socket.socket() # 1.新建socket
server.bind('127.0.0.1',8080) # 2.绑定
server.listen(5) # 3.监听
connect,address = server.accept() # 4.接受 connect为新的套接字对象、address为地址
print('connect addr:{}'.format(address))
content = connect.recv(1024) # 获取客户端消息 ==> hello world
print(str(content,encoding='utf-8'))
connect.close()

# client.py
import socket
client = socket.socket() # 1.新建
client.connect('127.0.0.1',8080) # 2.连接服务端
client.send(bytes('hello world',encoding='utf-8')) # 发送内容
client.close()

# python自带的HTTP服务器
# 启动
python -m http.server
python -m http.server 8080 -d D:/ # 指定启动 端口和目录路径

# 发送http请求:request(建议)、urllib 库
from urllib import request
response = request.urlopen('http://www.baidu.com') #发送请求
print(response)

import request
response = request.get('http://www.baidu.com')
print(response)
content = str(response.content,encoding = 'utf-8')
content_list = content.split('\n') # 分行
for line in content_list:
if 'www' in line:
print(line.strip())

7.函数式编程

编程范式

允许有变量,支持高阶函数(函数可作为变量),支持闭包(可返回函数),支持匿名函数

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 1.把函数作为参数
def add(x,y,f):
return f(x) +f(y)
add(2,3,abs) # abs为取绝对值函数

# 2.map:把函数作用于list里的每一个参数
map(f,list)
for item in map(abs,[-1,2,-3]):
print(item)

# 3.reduce:把函数作用于list里的每一个参数,该函数接收至少2个参数
def prod(x,y):
return x*y

print(reduce(prod,[1,3,5,7,9])) # 1*3*5*7*9

# 4.filter:过滤,符合条件才取
import math
def f(x):
r = int(math.sqrt(x))
if r*r == x: # 平方根为整数
return True
else:
return False
for item in filter(f,range(1,101)):
print(item) # 1,4,9,16...

# 5.sorted:自定义排序
sorted([23,12,25,66]) # ==> 12,23,25,66
score = [('Alice',23),('Coco',12),('Bob',25),('Dog',66)]
sorted(score) # 按第一个元素排序 ==> ('Alice',23),('Bob',25),('Coco',12),('Dog',66)
# 指定排序字段
def k(item):
return item[1] # 第二个字段
sorted(score,key = k, reverse=True) # 倒序 ==> [('Dog',66),('Bob',25),('Alice',23),('Coco',12)]
# 忽略大小写排序
def k(item):
return item.lower()
names = ['Bob','Alice','coco']
sorted(names,key = k)

# 6.返回函数:使用场景1-延迟执行
def f():
def sub_f():
print('call sub_f')
return sub_f
# 返回集合乘积
def cal_prod(l):
def prod(x,y): # 也可以嵌套进all_prod里定义
return x*y
def all_prod():
return reduce(prod,l)
return all_prod

l = [1,2,3]
f = cal_prod(l)
print(f()) # ==> 6 1*2*3

# 7.闭包
# 希望一次返回3个函数,分别计算1x1,2x2,3x3:
def count():
fs = []
for i in range(1, 4):
def f():
return i*i # i=3,i=3,i=3
fs.append(f)
return fs
f1, f2, f3 = count() # 全部返回9,因为调用的时候,i都等于3

def count():
fs = []
for i in range(1, 4):
def f(j):
print('j={}'.format(j)) # j=1,j=2,j=3
def g():
return j*j
return g
r = f(i)
fs.append(r)
return fs
f1, f2, f3 = count()
print(f1(), f2(), f3())

# 8.匿名函数:只能由一个表达式,不用return,返回值就是表达式的结果
# 定义:lambda
lambda x:x*x

from functools import reduce
reduce(lambda x, y: x + y, [1,3,5,7,9])

l = ['bob','Alice','Coco']
print(sorted(l,key=lambda x: x.lower()))

# 9.无参数的decorator:接收一个函数作为参数,返回一个新函数,[参考](https://www.jb51.net/article/134782.htm)
# 使用场景:日志、异常信息,类似java的AOP
f = decorate(f)
@

# 10.偏函数:创建一个调用另外一个部分参数或变量已经预置的函数
def int2(x, base=2): # 转二进制
return int(x, base)
import functools
int2 = functools.partial(int, base=2)
sorted_ignore_case = functools.partial(sorted, key=lambda item: item.lower())
sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
------ 本文结束感谢您的阅读 ------

本文标题:python初学习

文章作者:MangoCheng

发布时间:2022年03月20日 - 20:22:49

最后更新:2022年04月04日 - 09:21:47

原始链接:http://mangocheng.com/posts/58c3db0a.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。