写在前面:小白闲来无事,参考小甲鱼视频重温Python,所及笔记,仅供参考。第一次写长笔记,格式较乱,请谅解

一、数据类型

1、输入路径

>>>print("D:\three\two\one\now")
D:  hree    wo\one
ow

修改方法:

(1)每个反斜杠后面添加一个反斜杠

>>>print("D:\\three\\two\\one\\now")
D:\three\two\one\now

(2)字符串前添加“r”,使其成为原始字符串,转义符不再有效

>>>print(r"D:\three\two\one\now")
D:\three\two\one\now

2、反斜杠不能放在字符串末尾

放在末尾代表“这件事还未完事”

编写代码时如果一行没写完,可在本行代码最后加“\”在下一行继续编写

3、长字符串

采用三引号字符串(Triple quoted)

三个单引号或双引号都可以

但要前后呼应、成双成对

4、字符串格式化

(1)format()

>>> year = 2001
>>> "MrKun生于{}年".format(year)
'MrKun生于2001年'>>> "1+2={},2的平方是{},3的立方是{}".format(1+2,2*2,3*3*3)
'1+2=3,2的平方是4,3的立方是27'>>> "{}看到{}很激动".format("MrKun","迈凯伦")
'MrKun看到迈凯伦很激动'
>>> "{1}看到{0}很激动".format("MrKun","迈凯伦")
'迈凯伦看到MrKun很激动'>>> "{0}{0}{1}{1}".format("是","非")
'是是非非'>>> "我叫{name},我爱{fav}".format(name="MrKun",fav="Python")
'我叫MrKun,我爱Python'>>> "我叫{name},我爱{0},喜爱{0}的人运气都不会太差".format("Python",name="MrKun")
'我叫MrKun,我爱Python,喜爱Python的人运气都不会太差'

在字符串中输出{}

//法一:把{}当作要输入的字符串
>>> "{},{},{}".format(1,"{}",2)
'1,{},2'//法二:使用花括号注释花括号
>>> "{},{{}},{}".format(1,2)
'1,{},2'

(2)设置千分位分隔符

>>> "{:,}".format(1234)
'1,234'
>>> "{:_}".format(1234)
'1_234'
>>> "{:,}".format(123456789)
'123,456,789'

(3)位数限制

※对于[type]设置为’f或’F’的浮点数来说,是限定小数点后显示多少个数位
※对于[type]设置为’g’或’G’的浮点数来说,是限定小数点前后一共显示多少个数位
※对于非数字类型来说,限定的是最大字段的大小
※对于整数类型来说,则不允许使用[.precision]选项

#'f或'F'的浮点数
>>> "{:.2f}".format(3.1415)
'3.14'#'g'或'G'的浮点数
>>> "{:.2g}".format(3.1415)
'3.1'#非数字类型
>>> "{:.6}".format("I love Python")
'I love'#整数类型
>>> "{:.2}".format(520)
Traceback (most recent call last):File "<pyshell#23>", line 1, in <module>"{:.2}".format(520)
ValueError: Precision not allowed in integer format specifier

(4)type类型

#转化为二进制
>>> "{:b}".format(80)
'1010000'
#转化为Unicode字符
>>> "{:c}".format(80)
'P'
#转化为十进制
>>> "{:d}".format(80)
'80'
#转化为八进制
>>> "{:o}".format(80)
'120'
#转化为十六进制
>>> "{:x}".format(80)
'50'
#转化为二进制(带前缀)
>>> "{:#b}".format(80)
'0b1010000'
#转化为八进制(带前缀)
>>> "{:#o}".format(80)
'0o120'
#转化为十六进制(带前缀)
>>> "{:#x}".format(80)
'0x50'

(5)f-字符串

注:仅适用于Python3.6之后

>>> year = 2001
>>> F"MrKun生于{year}年"
'MrKun生于2001年'>>> f"1+2={1+2},2的平方是{2*2},3的立方是{3*3*3}"
'1+2=3,2的平方是4,3的立方是27'>>> f"{123456789:,}"
'123,456,789'

5、字符串的加法和乘法

(1)字符串加法

>>> 520+1314
1834
>>> '520'+'1314'
'5201314'

(2)字符串乘法

>>> print("重复十遍\n"*10)
重复十遍
重复十遍
重复十遍
重复十遍
重复十遍
重复十遍
重复十遍
重复十遍
重复十遍
重复十遍

6、random库实现伪随机数

import random

x = random.randint(a,b)

>>> import random
>>> random.randint(1,10)
9
>>> random.randint(1,10)
4
>>> random.randint(1,10)
3
>>> random.randint(100,10000)
3901

7、浮点数

因为采用IEEE754标准存储浮点数,导致精度误差

>>> 0.1 + 0.2
0.30000000000000004
>>> 0.3 == 0.1 + 0.2
False

解决方法:采用decimal模块
注:传入的是字符串

>>> import decimal
>>> a = decimal.Decimal('0.1')
>>> b = decimal.Decimal('0.2')
>>> print(a + b)
0.3
>>> c = decimal.Decimal('0.3')
>>> c == a + b
True

8、复数

>>> 1 + 2j
(1+2j)
>>> x = 1 + 2j
>>> x.real    //实部
1.0
>>> x.imag    //虚部
2.0

9、布尔类型

>>> bool(250)
True
>>> bool("假")
True
>>> bool("flase")
True
>>> bool(" ")
True
>>> bool("")
False
>>> bool(False)
False

bool()函数里的参数带双引号,代表为一个字符串,除了空字符串为假,其余字符串(包括空字符串)均为真;

数值情况下,只有取值为0时,才为False,其余情况均为真

>>> bool(520)
True
>>> bool(0)
False
>>> bool(0.0)
False
>>> bool(0j)
False

结果为False的所有情况

特殊记忆

>>> 1 == True
True
>>> 0 == False
True
>>> True + False
1
>>> True - False
1
>>> True * False
0
>>> True / False     #除数不能为0
Traceback (most recent call last):File "<pyshell#53>", line 1, in <module>True / False
ZeroDivisionError: division by zero

10、运算

(1)算术运算

①x//y(地板除)

取比目标结果小的最大整数

>>> 3/2
1.5
>>> 3//2
1
>>> -3//2
-2
### (2)逻辑运算

短路逻辑

>>> 3 and 4
4
>>> 3 or 4
3
>>> 0 and 3
0
>>> 0 or 4
4
>>> (not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9)
4

二、输入输出

1、输入

>>> temp = input("你是谁:")   #括号里内容为显示在屏幕上的提示语句
你是谁:MrKun     #MrKun为输入
>>> print(temp)
MrKun

三、分支结构

score = input("请输入你的分数:")
score = int(score)
if 0 <= score < 60:print("D")
elif 60 <= score < 80:print("C")
elif 80 <= score < 90:print("B")
elif 90 <= score < 100:print("A")
elif score == 100:print("S")
else:print("请输入 0~100 之间的分值!")

进阶:

#基本
>>> a = 3
>>> b = 5
>>> if a < b:small = a;
else:small = b;
>>> print(small)
3#进阶#>>> small = a if a < b else small = b  //small = b赋值式不能这样写
#SyntaxError: cannot assign to conditional expression
>>> small = a if a < b else b
>>> print(small)
3

四、循环结构

1、while循环

(1)while else 结构

循环正常结束退出,else语句正常执行,即有没有else一样

i = 1
while i < 5:print("循环内,i的值是",i)i += 1
else:print("循环外,i的值是",i)循环内,i的值是 1
循环内,i的值是 2
循环内,i的值是 3
循环内,i的值是 4
循环外,i的值是 5

循环不正常结束退出,else语句不执行

i = 1
while i < 5:print("循环内,i的值是",i)if i == 2:breaki += 1
else:print("循环外,i的值是",i)循环内,i的值是 1
循环内,i的值是 2

2、for循环

>>> for each in "abcdefg":print(each)a
b
c
d
e
f
g

range()函数

参数必须是整形,且不包括stop

(1)range(stop)

>>> for i in range(10):print(i)0
1
2
3
4
5
6
7
8
9

range(start,stop)

>>> for i in range(5,10):print(i)5
6
7
8
9

range(start,stop,step)

>>> for i in range(5,10,2):print(i)5
7
9>>> for i in range(10,5,-2):print(i)10
8
6

例:查找10以内的素数

>>> for n in range(2,10):for x in range(2,n):if(n % x == 0):breakelse:print(n,"是一个素数")2 是一个素数
3 是一个素数
5 是一个素数
7 是一个素数

五、列表

列表可以包含任何数据类型

1、定义

>>> [1,2,3,4,5]
[1, 2, 3, 4, 5]
>>> [1,2,3,4,5,"上山打老虎"]
[1, 2, 3, 4, 5, '上山打老虎']

2、遍历

>>> rhyme = [1,2,3,4,5,"上山打老虎"]
>>> print(rhyme)
[1, 2, 3, 4, 5, '上山打老虎']
>>> for each in rhyme:print(each)1
2
3
4
5
上山打老虎

3、获取某个元素

>>> rhyme[0]
1
>>> rhyme[1]
2

获取最后一个元素

(1)rhyme[最后一个元素位置]

>>> rhyme[5]
'上山打老虎'

(2)获取列表长度

>>> length = len(rhyme)
>>> rhyme[length-1]
'上山打老虎'

(3)rhyme[-1]

>>> rhyme[-1]
'上山打老虎'

4、列表切片

#输出前三个元素
>>> rhyme[0:3]
[1, 2, 3]#输出4-6个元素
>>> rhyme[3:6]
[4, 5, '上山打老虎']#改进
#输出前三个元素
>>> rhyme[:3]
[1, 2, 3]#输出4-6个元素
>>> rhyme[3:]
[4, 5, '上山打老虎']#输出全部元素
>>> rhyme[:]
[1, 2, 3, 4, 5, '上山打老虎']#间隔1输出元素
>>> rhyme[0:6:2]
[1, 3, 5]#改进
>>> rhyme[::2]
[1, 3, 5]#倒序间隔1输出元素
>>> rhyme[::-2]
['上山打老虎', 4, 2]#倒序输出元素
>>> rhyme[::-1]
['上山打老虎', 5, 4, 3, 2, 1]

5、增删改查

(1)增加元素

append() //在列表末尾增加单个元素

heros = ["钢铁侠","绿巨人"]
>>> heros.append("黑寡妇")
>>> heros
['钢铁侠', '绿巨人', '黑寡妇']

extend() //在列表末尾增加多个元素(可迭代对象)

>>> heros.extend(["鹰眼","灭霸","雷神"])
>>> heros
['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '灭霸', '雷神']

进阶

>>> s = [1,2,3,4,5]
>>> s[len(s):] = [6]   #等同于s.append(6)
>>> s
[1, 2, 3, 4, 5, 6]>>> s[len(s):] = [7,8,9]    #等同于s.extend[7,8,9]
>>> s
[1, 2, 3, 4, 5, 6, 7, 8, 9]

insert(待插入元素位置,待插入元素) //在任意位置插入元素

>>> s = [1,3,4,5]
#在第第二个位置插入元素2
>>> s.insert(1,2)
>>> s
[1, 2, 3, 4, 5]
#在第一个位置插入元素0
>>> s.insert(0,0)
>>> s
[0, 1, 2, 3, 4, 5]
在末尾插入元素6
>>> s.insert(len(s),6)
>>> s
[0, 1, 2, 3, 4, 5, 6]

(2)删除元素

remove() //删除指定元素

>>>heros = ['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '灭霸', '雷神']
>>> heros.remove("灭霸")
>>> heros
['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '雷神']

注:1.如果列表中存在多个匹配的元素,那么只会删除第一个

​ 2.如果指定的元素不存在,那么程序就会报错

pop() //删除指定位置的元素

>>>heros = ['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '雷神']
>>> heros.pop(2)
'黑寡妇'
>>> heros
['钢铁侠', '绿巨人', '鹰眼', '雷神']

clear() //清空列表中所有元素

>>>heros = ['钢铁侠', '绿巨人', '鹰眼', '雷神']
>>> heros.clear()
>>> heros
[]

(3)修改元素

>>> heros = ['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '灭霸', '雷神']
#修改单个元素
>>> heros[4] = "蜘蛛侠"
>>> heros
['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '蜘蛛侠', '雷神']#修改多个元素
>>> heros[3:] = ["武松","林冲","李逵"]
>>> heros
['钢铁侠', '绿巨人', '黑寡妇', '武松', '林冲', '李逵']

sort(key = None,reverse = False) //对列表排序

>>> nums = [3,1,9,6,8,3,5,3]
>>> nums.sort()          #默认从小到大排序
>>> nums
[1, 3, 3, 3, 5, 6, 8, 9]>>> nums = [3,1,9,6,8,3,5,3]
>>> nums.sort(reverse = True)    #从大到小排序
>>> nums
[9, 8, 6, 5, 3, 3, 3, 1]

reverse() //将列表元素进行反转

>>> nums = [3,1,9,6,8,3,5,3]
>>> nums.sort()
>>> nums.reverse()
>>> nums
[9, 8, 6, 5, 3, 3, 3, 1]>>> heros = ['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '灭霸', '雷神']
>>> heros.reverse()
>>> heros
['雷神', '灭霸', '鹰眼', '黑寡妇', '绿巨人', '钢铁侠']

(4)查找元素

count() //查找元素出现次数

>>> nums = [3,1,9,6,8,3,5,3]
>>> nums.count(3)
3

index(x,start,end) //查找索引值

>>> nums.index(3)
0
>>> nums.index(3,1,7)
5>>> heros = ['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '灭霸', '雷神']
>>> heros.index("黑寡妇")
2

注:index()函数返回的是该元素第一次出现的索引

例:结合index修改列表某一元素值

>>> heros = ['钢铁侠', '绿巨人', '黑寡妇', '鹰眼', '灭霸', '雷神']
>>> heros[ heros.index("黑寡妇")] = "神奇女侠"
>>> heros
['钢铁侠', '绿巨人', '神奇女侠', '鹰眼', '灭霸', '雷神']

copy() //复制列表

>>> nums = [3,1,9,6,8,3,5,3]
>>> nums_copy1 = nums.copy()
>>> nums_copy1
[3, 1, 9, 6, 8, 3, 5, 3]
>>> nums_copy2 = nums[:]
>>> nums_copy2
[3, 1, 9, 6, 8, 3, 5, 3]

6、列表的加法和乘法

>>> s = [1,2,3]
>>> t = [4,5,6]
>>> s + t
[1, 2, 3, 4, 5, 6]
>>> s * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

7、嵌套列表

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

遍历嵌套列表

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]>>> for i in matrix:for each in i:print(each)1
2
3
4
5
6
7
8
9

改进:

>>> for i in matrix:for each in i:print(each,end = ' ')print()1 2 3
4 5 6
7 8 9

访问具体某个元素

>>> matrix[0]      #访问某一行
[1, 2, 3]>>> matrix[1][1]    #访问具体某一个元素
5

利用嵌套创建列表

(1)创建一维列表

>>> A = [0] * 3
>>> A
[0, 0, 0]

(2)创建二维列表

for i in range(3):A[i] = [0] * 3>>> A
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]#错误方式
>>> B = [[0] * 3] * 3
>>> B
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

错误原因:

引入新的运算符 is

字符串存储

>>> x = "FishC"
>>> y = "FishC"
>>> x is y
True

存储结构示意图

列表存储

>>> x = [1,2,3]
>>> y = [1,2,3]
>>> x is y
False

存储结构示意图

上题

>>> A[0] is A[1]
False
>>> A[1] is A[2]
False
>>> B[0] is B[1]
True
>>> B[1] is B[2]
True

A的存储结构示意图

B的存储结构示意图

8、浅拷贝与深拷贝

(1)浅拷贝

对于一维列表

>>> x = [1,2,3]
>>> y = x
>>> x[1] = 1
>>> x
[1, 1, 3]
>>> y
[1, 1, 3]

存储结构示意图

y与x引用同一地址

>>> x = [1,2,3]
>>> y = x.copy()
>>> x[1] = 1
>>> x
[1, 1, 3]
>>> y
[1, 2, 3]

存储结构示意图

对于二维列表

>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> y = x.copy()
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]

原因:对于二位列表,copy()浅拷贝只拷贝外层外层对象,如果包含嵌套对象,那么拷贝的只是其引用

存储结构示意图

copy模块

>>> import copy
>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> y = copy.copy(x)   #浅拷贝
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]

(2)深拷贝

>>> import copy
>>> x = [[1,2,3],[4,5,6],[7,8,9]]
>>> y = copy.deepcopy(x)
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

原因:deepcopy函数将原对象拷贝的同时,也将对象中所有引用的子对象一并进行了拷贝(如果存在多层嵌套,深拷贝也会全部拷贝每一层的数据)

存储结构示意图:

为什么python默认为浅拷贝?

效率,浅拷贝比深拷贝效率高

9、列表推导式

[expression for target in iterable]

例:建一个列表元素从0-9

>>> x = [i for i in range(10)]
>>> x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

例:建一个列表元素从1-10

>>> x = [i + 1 for i in range(10)]
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

例:列表中存放字符*2

>>> x = [c * 2 for c in "MrKun"]
>>> x
['MM', 'rr', 'KK', 'uu', 'nn']

例:列表中元素扩大一倍

#法一:
>>> oho = [1,2,3,4,5]
>>> for i in range(len(oho)):oho[i] = oho[i] * 2>>> oho
[2, 4, 6, 8, 10]#法二:
>>> oho = [1,2,3,4,5]
>>> oho = [i * 2 for i in oho]
>>> oho
[2, 4, 6, 8, 10]

区别:for循环是直接修改源列表的元素;列表推导式则是重新创建一个新的列表,操作完成后,赋值为原先的变量名

例:取矩阵中每一行第二个元素

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> col2 = [row[1] for row in matrix]
>>> col2
[2, 5, 8]

例:取得矩阵左上角至右下角元素

>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> diag = [matrix[i][i] for i in range(len(matrix))]
>>> diag
[1, 5, 9]

进阶

(1)[expression for target in iterable if condition]

例:建一个十以内的偶数列表

>>> even = [i for i in range(10) if i % 2 == 0]
>>> even
[0, 2, 4, 6, 8]

语句执行顺序:

先执行for循环,然后if语句,最后执行赋值

证明:

>>> even = [i + 1 for i in range(10) if i % 2 == 0]
>>> even
[1, 3, 5, 7, 9]

例:寻找列表中M开头的单词

>>> words = ["Mike","MrKun","Jack","Amy","Ella","Monica"]
>>> mword = [w for w in words if w[0] == 'M']
>>> mword
['Mike', 'MrKun', 'Monica']

(2)[expression for target1 in iterable1

for target2 in iterable2

……

for targetN in iterableN]

外层循环在前面,内层循环在后面

例:将二维矩阵降维

#法一:
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> flatten = []
>>> for row in matrix:for col in row:flatten.append(col)>>> flatten
[1, 2, 3, 4, 5, 6, 7, 8, 9]#法二:
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> flatten = [col for row in matrix for col in row]
>>> flatten
[1, 2, 3, 4, 5, 6, 7, 8, 9]

例:笛卡尔积

#法一:
>>> _ = []
>>> for x in "mrkun":for y in "MRKUN":_.append(x + y)>>> _
['mM', 'mR', 'mK', 'mU', 'mN', 'rM', 'rR', 'rK', 'rU', 'rN', 'kM', 'kR', 'kK', 'kU', 'kN', 'uM', 'uR', 'uK', 'uU', 'uN', 'nM', 'nR', 'nK', 'nU', 'nN']#法二:
>>> [x + y for x in "mrkun" for y in "MRKUN"]
['mM', 'mR', 'mK', 'mU', 'mN', 'rM', 'rR', 'rK', 'rU', 'rN', 'kM', 'kR', 'kK', 'kU', 'kN', 'uM', 'uR', 'uK', 'uU', 'uN', 'nM', 'nR', 'nK', 'nU', 'nN']

(3)[expression for target1 in iterable1 if condition1

for target2 in iterable2 if condition2

……

for targetN in iterableN if conditionN]

例:十以内可被2整除的x与被3整除的y,构成的列表

#法一:
>>> _ = []
>>> for x in range(10):if x % 2 == 0:for y in range(10):if y % 3 == 0:_.append([x,y])>>> _
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]#法二:
>>> [[x,y] for x in range(10) if x % 2 == 0 for y in range(10) if y % 3 == 0]
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]

六、元组

1、基本形式

#(1)带括号
>>> rhyme = (1,2,3,4,5,"上山打老虎")
>>> rhyme
(1, 2, 3, 4, 5, '上山打老虎')#(2)不带括号
>>> rhyme = 1,2,3,4,5,"上山打老虎"
>>> rhyme
(1, 2, 3, 4, 5, '上山打老虎')

进阶:生成单个元素的元组

错误操作

>>> x = (520)
>>> x
520
>>> type(x)
<class 'int'>

正确操作

>>> x = (520,)
>>> x
(520,)
>>> type(x)
<class 'tuple'>

2、 基本操作

访问元组中元素

>>> rhyme = (1,2,3,4,5,"上山打老虎")
>>> rhyme[0]
1
>>> rhyme[5]
'上山打老虎'
>>> rhyme[-1]
'上山打老虎'

因为元组不能修改元素值,所以元组只支持查,不支持增删改

其余操作与列表类似,支持切片操作

count() //查询某一元素个数

>>> nums = (3,1,9,6,8,3,5,3)
>>> nums.count(3)
3

index() //查询某一元素索引

>>> heros = ("蜘蛛侠","绿巨人","黑寡妇")
>>> heros.index("黑寡妇")
2

拼接(+)

>>> s = (1,2,3)
>>> t = (4,5,6)
>>> s + t
(1, 2, 3, 4, 5, 6

重复(*)

>>> s = (1,2,3)
>>> s * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)

3、嵌套元组

>>> s = (1,2,3)
>>> t = (4,5,6)
>>> w = (s,t)    #括号可省略,写为w = s,t
>>> w
((1, 2, 3), (4, 5, 6))

4、列表推导式

元组也适用列表推导式,但是必须为[],不能为()

例:将元组各元素扩大一倍

>>> s = (1,2,3,4,5)
>>> [each * 2 for each in s]
[2, 4, 6, 8, 10]

5、打包与解包

(1)打包

将多个元素赋值给一个变量,称为打包

>>> t = (123,"MrKun",3.14)    #将123,"MrKun",3.14打包到一起
>>> t
(123, 'MrKun', 3.14)

(2)解包

将序列中的多个元素一次性赋值给多个变量名,称为解包

t = (123,"MrKun",3.14)
>>> x,y,z = t   #将123,"MrKun",3.14分别赋值给x,y,z
>>> x
123
>>> y
'MrKun'
>>> z
3.14

打包和解包适用于所有序列,如元组、列表、字符串

#列表的解包
>>> t = [123,"MrKun",3.14]
>>> x,y,z = t
>>> x
123
>>> y
'MrKun'
>>> z
3.14#字符串的解包
>>> a,b,c,d,e = "MrKun"
>>> a
'M'
>>> b
'r'
>>> c
'K'
>>> d
'u'
>>> e
'n'

注:字符串左边变量数量必须与序列中元素个数一致(除非使用),否则会报错*

#错误操作:
>>> a,b,c = "MrKun"
Traceback (most recent call last):File "<pyshell#99>", line 1, in <module>a,b,c = "MrKun"
ValueError: too many values to unpack (expected 3)#正确操作
>>> a,b,*c = "MrKun"
>>> a
'M'
>>> b
'r'
>>> c
['K', 'u', 'n']

6、进阶

(1)多重赋值

**原理:**先打包为元组,再解包

>>> x,y = 10,20
>>> x
10
>>> y
20

(2)修改元组值

虽然元组中元素值不可修改,但如果元组中元素为可修改序列,则可以修改改元素值

>>> s = [1,2,3]
>>> t = [4,5,6]
>>> w = (s,t)
>>> w
([1, 2, 3], [4, 5, 6])
>>> w[0][0] = 0
>>> w
([0, 2, 3], [4, 5, 6])

七、序列

1、拼接与重复

对于可修改序列,+、*是对原序列操作;

对于不可修改序列,+、*生成了一个新序列。

#可修改序列
>>> s = [1,2,3]
>>> id(s)
1929589562176
>>> s *=2
>>> s
[1, 2, 3, 1, 2, 3]
>>> id(s)
1929589562176#不可修改序列
>>> t = (1,2,3)
>>> id(t)
1929589890112
>>> t *= 2
>>> t
(1, 2, 3, 1, 2, 3)
>>> id(t)
1929589698720

2、is/is not

判断两个变量是否是同一个对象

>>> x = "MrKun"
>>> y = "MrKun"
>>> x is y
True
>>> x = [1,2,3]
>>> y = [1,2,3]
>>> x is y
False

3、in/not in

>>> "德斯" in "梅赛德斯奔驰"
True
>>> "Kun" in "MrKun"
True
>>> "Kun" not in "MrKun"
False

3、del

(1)删除对象

>>> x = "123"
>>> y = [1,2,3]
>>> del x,y
>>> x
Traceback (most recent call last):File "<pyshell#25>", line 1, in <module>x
NameError: name 'x' is not defined
>>> y
Traceback (most recent call last):File "<pyshell#26>", line 1, in <module>y
NameError: name 'y' is not defined

(2)删除序列中某些元素

#删除列表中1-4号的元素
#法一:切片
#原理:先把1-4号元素赋值为“ ”,再将后面的元素赋值到前面
>>> y = [1,2,3,4,5]
>>> y[1:4] = []
>>> y
[1, 5]#法二:del
>>> x = [1,2,3,4,5]
>>> del x[1:4]
>>> x
[1, 5]

(3)间隔删除

del可以间隔删除序列中元素,而切片不可以

#删除第0、2、4个元素
#错误操作(切片)
>>> x = [1,2,3,4,5]
>>> x[::2] = []
Traceback (most recent call last):File "<pyshell#40>", line 1, in <module>x[::2] = []
ValueError: attempt to assign sequence of size 0 to extended slice of size 3#del
>>> y = [1,2,3,4,5]
>>> del y[::2]
>>> y
[2, 4]

进阶

用del实现clear方法

x.clear()方法是清空序列中所有元素,但保留该对象

del x 则是删掉该对象

#clear
>>> x = [1,2,3,4,5]
>>> x.clear()
>>> x
[]#del
>>> y = [1,2,3,4,5]
>>> del y[:]
>>> y
[]

4、常用操作

(1)列表、元组和字符串相互转换

①list() //可迭代对象转换为列表

>>> list("MrKun")
['M', 'r', 'K', 'u', 'n']
>>> list((1,2,3,4,5))
[1, 2, 3, 4, 5]

②tuple() //可迭代对象转换为元组

>>> tuple("MrKun")
('M', 'r', 'K', 'u', 'n')
>>> tuple([1,2,3,4,5])
(1, 2, 3, 4, 5)

③str() //可迭代对象转换为字符串

>>> str((1,2,3,4,5))
'(1, 2, 3, 4, 5)'
>>> str([1,2,3,4,5])
'[1, 2, 3, 4, 5]'

(2)最大值与最小值

>>> s = [1,2,3,4,5]
>>> min(s)
1
>>> t = "MrKun"
>>> max(t)
'u'

注:空序列进行比较会报错

//设置默认值,在序列为空时输出默认值

>>> s = []
>>> min(s)
Traceback (most recent call last):File "<pyshell#62>", line 1, in <module>min(s)
ValueError: min() arg is an empty sequence
>>> min(s,default = "屁,啥都没有,怎么找到最小")
'屁,啥都没有,怎么找到最小'

(3)求和

sum()

>>> s = [1,0,0,8,6]
>>> sum(s)
15#初值为100,对序列求和
>>> sum(s,start = 100)
115

(4)sorted()与reversed()

①sorted()

>>> s = [1,2,3,0,6]
>>> sorted(s)
[0, 1, 2, 3, 6]#reverse = True,反向排序
>>> sorted(s,reverse = True)
[6, 3, 2, 1, 0]
>>> t = ["MrKun","Apple","Book","Banana","Pen"]
>>> sorted(t)   #对比每一个元素的第一个元素的编码值
['Apple', 'Banana', 'Book', 'MrKun', 'Pen']>>> sorted(t,key = len)     #每一个元素先执行一下len()函数,比较len()函数的返回结果
['Pen', 'Book', 'MrKun', 'Apple', 'Banana']

进阶

sorted()与sort()区别:

1.sorted()为函数;sort()为方法

2.sorted()是生成一个新序列,对原序列不产生影响;sort()对原序列重新排序

>>> s = [1,2,3,0,6]
>>> sorted(s)
[0, 1, 2, 3, 6]
>>> s
[1, 2, 3, 0, 6]>>> s.sort()
>>> s
[0, 1, 2, 3, 6]

3.sorted()可操作任何序列(队列、元组、字符串);sort()只能对队列操作

②reversed()

reversed()返回的是迭代器

>>> s = [1,2,5,8,0]
>>> reversed(s)
<list_reverseiterator object at 0x000001C144855730>
>>> list(reversed(s))
[0, 8, 5, 2, 1]

reversed()可操作任何序列

>>> list(reversed("MrKun"))
['n', 'u', 'K', 'r', 'M']
>>> list(reversed((1,2,5,9,3)))
[3, 9, 5, 2, 1]
>>> list(reversed(range(0,10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

(5)all()与any()

all() //判断是否所有元素的值都为真

any() //判断是否存在元素的值为真

>>> x = [1,1,0]
>>> y = [1,1,9]
>>> all(x)
False
>>> all(y)
True
>>> any(x)
True
>>> any(y)
True

(6)enumerate()

enumerate0函数用于返回一个枚举对象,它的功能就是将可迭代对象中的每个元素及从0开始的序号共同构成一个二元组的列表。

>>> seasons = ["Spring","Summer","Fall","Winter"]
>>> enumerate(seasons)     #返回一个可迭代对象
<enumerate object at 0x000002250564A1C0>
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons,10))   #自定义开始的序列
[(10, 'Spring'), (11, 'Summer'), (12, 'Fall'), (13, 'Winter')]

(7)zip()

z0函数用于创建一个聚合多个可迭代对象的迭代器。它会将作为参数传入的每个可迭代对象的每个元素依次组合成元组,即第ⅰ个元组包含来自每个参数的第ⅰ个元素。

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> zipped = zip(x,y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> z = (7,8,9)
>>> zipped = zip(x,y,z)
>>> list(zipped)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

进阶:

当序列元素数量不同时

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> z = "MrKun"
>>> zipped = zip(x,y,z)
>>> list(zipped)
[(1, 4, 'M'), (2, 5, 'r'), (3, 6, 'K')]

如果不想丢掉元素

>>> x = [1,2,3]
>>> y = [4,5,6]
>>> z = "MrKun"
>>> import itertools
>>> zipped = itertools.zip_longest(x,y,z)
>>> list(zipped)
[(1, 4, 'M'), (2, 5, 'r'), (3, 6, 'K'), (None, None, 'u'), (None, None, 'n')]

(8)map()

map0函数会根据提供的函数对指定的可迭代对象的每个元素进行运算,并将返回运算结果的迭代器

>>> mapped = map(ord,"MrKun")    #ord(),输出元素的Unicode编码
>>> list(mapped)
[77, 114, 75, 117, 110]
>>> mapped = map(pow,[2,3,10],[5,2,3])     #求n次方
>>> list(mapped)
[32, 9, 1000]
>>> list(map(max,[1,3,5],[2,2,2],[0,3,9,8]))      #以最小序列为准
[2, 3, 9]

(9)filter()

filter(0函数会根据提供的函数对指定的可迭代对象的每个元素进行运算,并将运算结果为真的元素,以迭代器的形式返回。

>>> list(filter(str.islower,"MrKun"))
['r', 'u', 'n']

(10)迭代器VS迭代对象

可迭代对象可以重复使用,而迭代器是一次性的

八、字典

1、创建字典

#六种方式
>>> a = {"吕布":"口口布","关羽":"关习习","刘备":"刘Baby"}
>>> b = dict(吕布="口口布",关羽="关习习",刘备="刘Baby")
>>> c = dict([("吕布","口口布"),("关羽","关习习"),("刘备","刘Baby")])
>>> d = dict({"吕布":"口口布","关羽":"关习习","刘备":"刘Baby"})
>>> e = dict({"吕布":"口口布","关羽":"关习习"},刘备="刘Baby")
>>> f = dict(zip(["吕布","关羽","刘备"],["口口布","关习习","刘Baby"]))
>>> a == b == c == d == e == f
True

2、增删改查

(1)增加元素

>>> x = {"吕布":"口口布","关羽":"关习习"}
>>> x["刘备"] = "刘Baby"
>>> x
{'吕布': '口口布', '关羽': '关习习', '刘备': '刘Baby'}

fromkeys(iterable[,values])

#创建一个初值相等的字典
>>> x = dict.fromkeys("MrKun",190)
>>> x
{'M': 190, 'r': 190, 'K': 190, 'u': 190, 'n': 190}
#修改某一项的值
>>> x['M'] = 70
>>> x
{'M': 70, 'r': 190, 'K': 190, 'u': 190, 'n': 190}
#该项如果不存在,创建这一项
>>> x['S'] = 89
>>> x
{'M': 70, 'r': 190, 'K': 190, 'u': 190, 'n': 190, 'S': 89}

序列中元素可以重复,字典中的项不会重复

(2)删除元素

①删除某一项

pop()

>>> x = dict.fromkeys("MrKun",190)
>>> x
{'M': 190, 'r': 190, 'K': 190, 'u': 190, 'n': 190}
#弹出指定项
>>> x.pop("K")
190
#该字典中不存在此项
>>> x
{'M': 190, 'r': 190, 'u': 190, 'n': 190}
>>> x.pop("坤")                 #如果弹出的项不存在,则抛出异常
Traceback (most recent call last):File "<pyshell#29>", line 1, in <module>x.pop("坤")
KeyError: '坤'
>>> x.pop("坤","没有")          #设置弹出的项不存在时,弹出的默认值
'没有'

popitem()

python 3.7 之前,字典无序,弹出随机一个项;python 3.7 之后,字典有序,弹出最后一个项。

>>> x.popitem()
('n', 190)
>>> x
{'M': 190, 'r': 190, 'u': 190}

del

del x[“key”] 删除某一项

>>> x = {'M': 190, 'r': 190, 'u': 190}
>>> del x['r']
>>> x
{'M': 190, 'u': 190}

del x 删除整个字典

>>> del x
>>> x
Traceback (most recent call last):File "<pyshell#36>", line 1, in <module>x
NameError: name 'x' is not defined

clear()

清空字典中所有项

>>> x = dict.fromkeys("MrKun",190)
>>> x
{'M': 190, 'r': 190, 'K': 190, 'u': 190, 'n': 190}
>>> x.clear()
>>> x
{}

(3)修改元素

直接修改

>>> d = dict.fromkeys("MrKun")
>>> d
{'M': None, 'r': None, 'K': None, 'u': None, 'n': None}
>>> d['r'] = 54
>>> d
{'M': None, 'r': 54, 'K': None, 'u': None, 'n': None}

update()

>>> d = {'M': None, 'r': 54, 'K': None, 'u': None, 'n': None}
>>> d.update({"M":62,"u":36})
>>> d
{'M': 62, 'r': 54, 'K': None, 'u': 36, 'n': None}

(4)查找元素

d[‘key’]

>>> d = {'M': None, 'r': 54, 'K': None, 'u': None, 'n': None}
>>> d['u']
36>>> d['U']       #该键不存在则会报错
Traceback (most recent call last):File "<pyshell#8>", line 1, in <module>d['U']
KeyError: 'U'

d.get()

查找,如果有该键值对,则返回对应值;没有则返回默认值

>>> d = {'M': None, 'r': 54, 'K': None, 'u': None, 'n': None}
>>> d.get('u',"Unicode")      #存在‘u’键,返回对应值
36
>>> d.get('U',"Unicode")      #不存在‘U’键,返回默认值“Unicode”
'Unicode'

d.setdefault()

查找字典,如果有该键值对,则返回对应值;没有则建立该键值对

>>> d = {'M': None, 'r': 54, 'K': None, 'u': None, 'n': None}
>>> d.setdefault('u',"Unicode")
36
>>> d.setdefault('U',"Unicode")
'Unicode'
>>> d
{'M': 62, 'r': 54, 'K': None, 'u': 36, 'n': None, 'U': 'Unicode'}

3、常用操作

(1)items()、keys()、values()

items() 获取字典的键值对的视图对象

keys() 获取字典的键的视图对象

values() 获取字典的值的视图对象

>>> d = {'M': 62, 'r': 54, 'K': 'Kiko', 'u': 36, 'n': 56, 'U': 'Unicode'}
>>> keys = d.keys()
>>> values = d.values()
>>> items = d.items()
>>> keys
dict_keys(['M', 'r', 'K', 'u', 'n', 'U'])
>>> values
dict_values([62, 54, 'Kiko', 36, 56, 'Unicode'])
>>> items
dict_items([('M', 62), ('r', 54), ('K', 'Kiko'), ('u', 36), ('n', 56), ('U', 'Unicode')])

因为获取的是视图对象,因此是动态改变的

#接上例。弹出一对键值对后,keys、values、items发生对应改变
>>> d.pop(‘K’)
'Kiko'
>>> keys
dict_keys(['M', 'r', 'u', 'n', 'U'])
>>> values
dict_values([62, 54, 36, 56, 'Unicode'])
>>> items
dict_items([('M', 62), ('r', 54), ('u', 36), ('n', 56), ('U', 'Unicode')])
>>>

(2)len()

获取字典中键值对数目

>>> d = {'M': 62, 'r': 54, 'u': 36, 'n': 56, 'U': 'Unicode'}
>>> len(d)
5

(3) in 、not in

>>> 'n' in d
True
>>> 'N' not in d
True

(4)字典转换为列表

list()

将字典转换为列表

#默认将字典的键转换为列表
>>> list(d)
['M', 'r', 'u', 'n', 'U']
#等同于list(d.keys())
>>> list(d.keys())
['M', 'r', 'u', 'n', 'U']#将字典的值转换为列表
>>> list(d.values())
[62, 54, 36, 56, 'Unicode']

(5)iter()

迭代器

>>> e = iter(d)
>>> next(e)
'M'
>>> next(e)
'r'
>>> next(e)
'u'
>>> next(e)
'n'
>>> next(e)
'U'
>>> next(e)
Traceback (most recent call last):File "<pyshell#39>", line 1, in <module>next(e)
StopIteration

(6)reversed()

将字典逆序输出

注:只适用于Python 3.8 之后

>>> list(reversed(d))        #将字典的键逆序输出
['U', 'n', 'u', 'r', 'M']
>>> list(reversed(d.keys()))
['U', 'n', 'u', 'r', 'M']>>> list(reversed(d.values()))    #将字典的值逆序输出
['Unicode', 56, 36, 54, 62]

4、嵌套字典

(1)字典嵌套字典

>>> d = {"吕布":{"语文":60,"数学":70,"英语":80},"关羽":{"语文":80,"数学":90,"英语":70}}
>>> d["吕布"]["数学"]
70

(2)字典嵌套序列

>>> d = {"吕布":[60,70,80],"关羽":[80,90,70]}
>>> d["吕布"][1]
70

5、字典推导式

例:将字典中键与值交换位置

>>> d = {'M':70,'r':105,'K':115,'u':104,'n':67}
>>> b = {v:k for k,v in d.items()}
>>> b
{70: 'M', 105: 'r', 115: 'K', 104: 'u', 67: 'n'}>>> c = {v:k for k,v in d.items() if v >100}
>>> c
{105: 'r', 115: 'K', 104: 'u'}

例:输出字符串的编码

>>> d = {x:ord(x) for x in "MrKun"}
>>> d
{'M': 77, 'r': 114, 'K': 75, 'u': 117, 'n': 110}
>>> d = {x:y for x in [1,3,5] for y in [2,4,6]}
>>> d
{1: 6, 3: 6, 5: 6}

九、集合

1、创建集合

(1)直接

>>> {"Java","Python"}
{'Python', 'Java'}

(2)集合推导式

>>> {s for s in "MrKun"}
{'K', 'r', 'n', 'u', 'M'}

(3)set()

>>> set("MrKun")
{'K', 'r', 'n', 'u', 'M'}

集合内元素是无序、唯一(不可重复)的

2、常用操作

(1)copy()

>>> s = {1,2,3,4,5}
>>> t = s.copy()
>>> t
{1, 2, 3, 4, 5}

(2)isdisjoint()

判断集合与给定集合有误关系

>>> s = set("MrKun")
>>> s
{'K', 'r', 'n', 'u', 'M'}
>>> s.isdisjoint(set("Python"))     #s集合中的'n'与给定集合中的'n'相等
False
>>> s.isdisjoint(set("Java"))       #s集合与给定集合无关系
True

(3)issubset()

判断集合是否是给定集合的子集

>>> s = set("MrKun")
>>> s
{'K', 'r', 'n', 'u', 'M'}
>>> s.issubset("666MrKun666")
True

(4)issuperset()

判断集合是否是给定集合的超集

>>> s = set("MrKun")
>>> s
{'K', 'r', 'n', 'u', 'M'}
>>> s.issuperset("Kun")
True

(5)union()

并集

>>> s = set("MrKun")
>>> s.union({1,2,3})
{1, 'u', 2, 3, 'r', 'M', 'K', 'n'}

(6)intersection()

交集

>>> s = set("MrKun")
>>> s.intersection("Kun")
{'K', 'u', 'n'}

(7)difference()

差集

>>> s = set("MrKun")
>>> s.difference("Kun")
{'r', 'M'}

以上所有方法均支持多参数

例:

>>> s = set("MrKun")
>>> s.union({1,2,3},"Python")
{'y', 1, 2, 3, 'r', 'K', 'o', 'h', 'n', 'u', 'P', 'M', 't'}

(8)symmetric_difference()

对称差集:对于两个集合A、B,先排除集合A与集合B的所有共同元素,由剩余的元素组成的集合,叫做集合A与集合B的对称差集

此方法不支持多参数

>>> s = set("MrKun")
>>> s.symmetric_difference("Python")
{'y', 'h', 'K', 'r', 'o', 'u', 'P', 'M', 't'}

提升

>>> s = set("MrKun")
#判断s是否是后面的子集
>>> s<= set("MrKun")
True
#判断s是否是后面的真子集
>>> s <= set("MrKun")
True
#判断s是否是后面的超集
>>> s > set("MrKun")
False
#判断s是否是后面的真超集
>>> s >= set("MrKun")
True
#并集
>>> s | {1,2,3} | set("Python")
{'y', 1, 2, 3, 'h', 'r', 'K', 'n', 'u', 'o', 'P', 'M', 't'}
#交集
>>> s & set("know") & set("Python")
{'n'}
#差集
>>> s - set("know") - set("Python")
{'K', 'u', 'r', 'M'}
#对称差集
>>> s ^ set ("Python")
{'y', 'r', 'K', 'o', 'h', 'u', 'P', 'M', 't'}

注:采用运算符简写时,运算符两侧都要是集合形式;采用方法时可以使用可迭代对象

>>> s = set("MrKun")
>>> s <= "MrKun"
Traceback (most recent call last):File "<pyshell#36>", line 1, in <module>s <= "MrKun"
TypeError: '<=' not supported between instances of 'set' and 'str'

(9)set()、frozenset()

set()生成的集合可以修改;frozenset()生成的集合不可修改

>>> s = set("MrKun")
>>> s
{'u', 'M', 'r', 'n', 'K'}
>>> t = frozenset("MrKun")
>>> t
frozenset({'u', 'M', 'r', 'n', 'K'})
>>> s.update([1,2],"34")   #set()生成的集合可以进行修改
>>> s
{'u', 1, 2, '4', 'M', 'r', '3', 'n', 'K'}
>>> t.update([1,2],"34")    #frozenset()生成的集合不可进行修改
Traceback (most recent call last):File "<pyshell#7>", line 1, in <module>t.update([1,2],"34")
AttributeError: 'frozenset' object has no attribute 'update'

(10)增加元素

update()

>>> s = set("MrKun")
>>> s
{'u', 'M', 'r', 'n', 'K'}
>>> s.update([1,2],"34")
>>> s
{'u', 1, 2, '4', 'M', 'r', '3', 'n', 'K'}

add()

>>> s = set("MrKun")
>>> s
{'u', 'M', 'r', 'n', 'K'}
>>> s.add("45")
>>> s
{'u', 'M', 'r', '45', 'n', 'K'}

update()与add()的区别

update()传入字符串是迭代获取其中每一个字符作为一个元素插入集合;

add()是将整个字符串作为一个元素插入集合。

>>> s = set("MrKun")
>>> s.intersection_update("Python")    #将原集合更新为交集
>>> s
{'n'}
>>> s = set("MrKun")
>>> s.difference_update("Python")     #将原集合更新为差集
>>> s
{'u', 'M', 'r', 'K'}
>>> s = set("MrKun")
>>> s.symmetric_difference_update("Python")     #将原集合更新为对称差集
>>> s
{'u', 'M', 'h', 'r', 'o', 'y', 'P', 'K', 't'}

(11)删除元素

remove()

>>> s = set("MrKun")
>>> s.remove("r")        #集合中存在'r',正常删除
>>> s
{'u', 'M', 'n', 'K'}
>>> s.remove("BMW")     #集合中不存在'BMW',报错
Traceback (most recent call last):File "<pyshell#37>", line 1, in <module>s.remove("BMW")
KeyError: 'BMW'

discard()

>>> s = set("MrKun")
>>> s.discard('r')     #集合中存在'r',正常删除
>>> s
{'u', 'M', 'n', 'K'}
>>> s.discard("BMW")   #集合中不存在'BMW',静默
>>> s
{'u', 'M', 'r', 'n', 'K'}

remove()与discard()的区别

传入参数存在情况下,结果相同;

传入参数不存在时,remove()报错,discard()静默。

pop()

随机弹出某一元素

>>> s = {'u', 'M', 'n', 'K'}
>>> s.pop()
'u'
>>> s.pop()
'M'

疑问:为什么是顺序弹出的?

解答:因为本身集合元素存储时是随机的,所以从前往后弹出是属于随机的。

(3)嵌套集合

>>> x = {1,2,3}
>>> y = {x,4,5}
Traceback (most recent call last):File "<pyshell#52>", line 1, in <module>y = {x,4,5}
TypeError: unhashable type: 'set'

因为只有不可变的量才可以作为集合元素,所以无法直接嵌套

解决方法:frozenset()

>>> x = {1,2,3}
>>> x = frozenset(x)
>>> y = {x,4,5}
>>> y
{frozenset({1, 2, 3}), 4, 5}

十、函数

1、基本使用

(1)函数定义

>>> def myfunc():pass>>> myfunc()>>> def myfunc():for i in range(3):print("I love Python")>>> myfunc()
I love Python
I love Python
I love Python

(2)参数

单个参数

>>> def myfunc(name):for i in range(3):print(f"I love {name}")>>> myfunc("Java")
I love Java
I love Java
I love Java

多个参数

>>> def myfunc(name,times):for i in range(times):print(f"I love {name}")>>> myfunc("Python",5)
I love Python
I love Python
I love Python
I love Python
I love Python

位置参数

>>> def myfunc(s,vt,o):return "".join((o,vt,s))
#参数位置需要对齐
>>> myfunc("我","喜欢","Pyhon")
'Pyhon喜欢我'

关键字参数

>>> myfunc(o = "我", vt = "喜欢", s = "Pyhon")
'我喜欢Pyhon'

注:位置参数必须在关键字参数之前

>>> myfunc(o="我","喜欢","Python")
SyntaxError: positional argument follows keyword argument

默认参数

形参给定默认值,如果实参为给定该值,则使用默认值。

>>> def myfunc(s,vt,o = "MrKun"):return "".join((o,vt,s))>>> myfunc("Python","喜欢")
'MrKun喜欢Python'
>>> myfunc("Python","喜欢","SSK")
'SSK喜欢Python'

注:位置参数必须在默认参数之前

#默认参数放在位置参数前面,报错
>>> def myfunc(s="苹果",vt,o = "MrKun"):return "".join((o,vt,s))
SyntaxError: non-default argument follows default argument#默认参数放在位置参数后面
>>> def myfunc(vt,s="苹果",o = "MrKun"):return "".join((o,vt,s))>>> myfunc("喜欢")
'MrKun喜欢苹果'

收集参数

参数前面加*变成收集参数

>>> def myfunc(*args):print("有{}个参数".format(len(args)))print("第2个参数是:{}".format(args[1]))>>> myfunc(1,2,3,4,5)
有5个参数
第2个参数是:2>>> def myfunc(*args):print(args)print(type(args))>>> myfunc(1,2,3,4,5)
(1, 2, 3, 4, 5)
<class 'tuple'>

原理:利用元组的打包和解包。传入的参数,打包成一个元组。

进阶

如果形参既有收集参数,又有默认参数怎么办

>>> def myfunc(*args,a,b):print(args,a,b)>>> myfunc(1,2,3,4,5)
Traceback (most recent call last):File "<pyshell#33>", line 1, in <module>myfunc(1,2,3,4,5)
TypeError: myfunc() missing 2 required keyword-only arguments: 'a' and 'b'

解决方法:使用关键字参数

>>> def myfunc(*args,a,b):print(args,a,b)>>> myfunc(1,2,3,a=4,b=5)
(1, 2, 3) 4 5

收集参数也可以是词典,采用**

>>> def myfunc(**kwargs):print(kwargs)>>> myfunc(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}

混合参数

>>> def myfunc(a,*b,**c):print(a,b,c)>>> myfunc(1,2,3,4,x=5,y=6)
1 (2, 3, 4) {'x': 5, 'y': 6}

解包参数

将元组解包 采用*

>>> args = (1,2,3,4,5)
>>> def myfunc(a,b,c,d,e):print(a,b,c,d,e)>>> myfunc(args)      #此时认为传入为一个参数,报错
Traceback (most recent call last):File "<pyshell#47>", line 1, in <module>myfunc(args)
TypeError: myfunc() missing 4 required positional arguments: 'b', 'c', 'd', and 'e'
>>> myfunc(*args)    #采用*解包
1 2 3 4 5

将字典解包 采用**

>>> args = (1,2,3,4,5)
>>> def myfunc(a,b,c,d,e):print(a,b,c,d,e)>>> kwargs = {'a':1,'b':2,'c':3,'d':4,'e':5}
>>> myfunc(**kwargs)    #采用**解包
1 2 3 4 5

(3)函数的返回值

>>> def div(x,y):if (y == 0):return "除数不能为0!"else:return x / y>>> div(4,2)
2.0
>>> div(4,0)
'除数不能为0!'

如果函数没有用return返回值,函数执行结束后也会返回一个None

>>> def myfunc():pass>>> print(myfunc())
None

(4)变量

如果有全局变量,在函数内可以访问全局变量,但一旦进行赋值操作,即创建了一个重名的局部变量

>>> x = 880
>>> def myfunc():print(x)   #此时x为全局变量>>> myfunc()
880>>> def myfunc():    x = 550        #此时为新建一个名为x的变量print(x)>>> myfunc()
550             #x = 550
>>> x           #全局变量 x = 880
880

修改全局变量方法:

global

不建议修改全局变量,避免带来意想不到的bug

>>> x = 880
>>> def myfunc():global x     #此处x为全局变量xx = 520      #将全局变量x的值修改为520print(x)>>> myfunc()
520
>>> x
520

(5)嵌套函数

>>> def funA():x = 520def funB():x = 880print("In funB,x = ",x)funB()print("In funA,x = ",x)>>> funA()
In funB,x =  880
In funA,x =  520

nonlocal 修改外层函数变量值

>>> def funA():x = 520def funB():nonlocal xx = 880print("In funB,x = ",x)funB()print("In funA,x = ",x)>>> funA()
In funB,x =  880
In funA,x =  880

# Python基础笔记(未完待续)相关推荐

  1. 深度学习(三)theano学习笔记(2)基础函数-未完待续

    theano学习笔记(2)基础函数 1.随机函数库的调用 2.卷积神经网络 [python] view plaincopy #-*-coding:utf-8-*- import theano impo ...

  2. TS学习笔记 ---未完待续....

    TS学习笔记 1 .ts文件与.tsx文件有什么区别 2.使用TS之前需要配置 3.TS特性 泛型和类型注解有什么区别? 3.什么是泛型参数? 4.函数.类.接口有什么区别? 4.1 一个class不 ...

  3. Python 基础整理(未完)

    数据类型和变量: 整数:Python可以处理任意大小的整数,当然包括负整数,在程序中的表示方法和数学上的写法一模一样,例如:1,100,-8080,0,等等. 计算机由于使用二进制,所以,有时候用十六 ...

  4. 火箭发射理论(基础篇-未完待续)//2021-1-27

    前言: 嗯,这个就没有那么多为什么了,浩瀚星海,对于人类而言,这是探索宇宙的第一步吧,所以对于我这种只有几十年生命周期的普通生物而言,这不言而喻.正如康德所言:有两种东西,我对它们的思考越是深沉和持久 ...

  5. JNI方面的笔记(未完待续)

    Microsoft Windows [版本 6.1.7600] 版权所有 (c) 2009 Microsoft Corporation.保留所有权利. C:\Users\toto>javah 用 ...

  6. jQuery基础(未完待续)

    1.       jQuery核心函数 jQuery也可写$,通常情况下$可能会与其他框架中的对象冲突(php有$的用法),所以如果所用的框架没有$的用法,jQuery可用$代替 (1)$(docum ...

  7. Java并发笔记-未完待续待详解

    为什么需要并行?– 业务要求– 性能并行计算还出于业务模型的需要– 并不是为了提高系统性能,而是确实在业务上需要多个执行单元.– 比如HTTP服务器,为每一个Socket连接新建一个处理线程– 让不同 ...

  8. 脚本基础(未完待续)

    脚本执行 1.赋予权限,chmod 755 hello.sh  ./hello.sh 2.通过bash执行脚本,bash hello.sh bash快捷键 dos2unix 文件名  windows文 ...

  9. pythonb超分辨成像_Papers | 超分辨 + 深度学习(未完待续)

    1. SRCNN 1.1. Contribution end-to-end深度学习应用在超分辨领域的开山之作(非 end-to-end 见 Story.3 ). 指出了超分辨方向上传统方法( spar ...

  10. Python基础:内置异常(未完待续)

    Python基础:内置异常(未完待续) 参考文章: (1)Python基础:内置异常(未完待续) (2)https://www.cnblogs.com/luo630/p/9176768.html 备忘 ...

最新文章

  1. Apriori算法通俗详解_fpgrowth2_关联分析评估
  2. 详解 Mysql LEFT JOIN和JOIN查询区别及原理
  3. TxQueryRunner类对结果集封装成bean、map及object的操作
  4. c语言哈希表电子辞典_关于redis涉及的知识点,C语言如何操作redis
  5. 2019寒假作业二:PTA7-1币值转换
  6. python绘制3维图-Python 画出来六维图
  7. 唔... 突然发现进入推荐博客了
  8. JVM JRE JDK,这些东西到底是什么?(转载)
  9. vue基础(学习官方文档)
  10. 存储过程循环遍历一个月的每一天的函数_JavaScript 循环:如何处理 async/await
  11. [转载] 【基础教程】Python input()函数:获取用户输入的字符串
  12. Server 2012使用Windows PowerShell cmdlet安装角色和角色服务功能
  13. MIUI V5正式发布 全部功能展示PPT回看
  14. int 转CString
  15. 选择对话框 android_Android日期时间选择器对话框
  16. 企业微信应用权限签名api记录
  17. java 类的对象是什么意思_java中类和对象的概念
  18. Python简单模拟微信发红包
  19. sina股票接口更新:Kinsoku jikou desu
  20. uniapp 开发微信公众号H5 隐藏右上角扩展按钮

热门文章

  1. 2021年5月审核员考试《认证通用基础》审核员考试真题
  2. C语言改变变量指定位置值
  3. 个人博客搭建具体操作
  4. 剑指offer目前遇到的函数
  5. chainer-骨干网络backbone-MnasNet代码重构【附源码】
  6. AE 动效制作和交付方案
  7. JVM笔记-13运行时数据区-堆(OOM、年轻代老年代)
  8. 信息技术服务标准(ITSS)系列培训 IT服务工程师/服务项目经理培训通知
  9. 超越顾客期望,企业必须了解的5件事儿
  10. PySeison-教程3:ADCP类