目录

  • 0. Jupyter Notebook简介

    • 0.1 Jupyter Notebook简介及启动

      • 0.1.1 Jupyter Notebook简介
      • 0.1.2 Jupyter Notebook安装与启动
    • 0.2 Jupyter Notebook里面的最常用的操作:
      • 0.2.1 更改文件名
      • 0.2.2 模式切换
      • 0.2.3 命令模式快捷键
      • 0.2.4 查询帮助
  • 1. Python基础语法
    • 1.1 编码
    • 1.2 标识符
    • 1.3 注释
    • 1.4 行与缩进
    • 1.5 多行语句
    • 1.6 多个变量赋值
    • 1.7 输入输出
    • 1.8 包的导入
    • 1.9 pip
  • 2. Python运算符
    • 2.1 算术运算符
    • 2.2 比较(关系)运算符
    • 2.3 赋值运算符
    • 2.4 逻辑运算
    • 2.5 位运算
    • 2.6 成员运算符
    • 2.7 身份运算符
    • 2.8 运算符优先级
  • 3. Python数据类型
    • 3.1 Number(数字)

      • 3.1.1 包括的类型
      • 3.1.2 数值运算
      • 3.1.3 数字类型转换
      • 3.1.4 数值型相关的函数
    • 3.2 String(字符串)
      • 3.2.1 字符串的索引
      • 3.2.2 字符串的切片
      • 3.2.3 字符串的操作符
      • 3.2.4 字符串函数
    • 3.3 List(列表)
      • 3.3.1 list的声明
      • 3.3.2 list的索引与切片
      • 3.3.3 List运算符
      • 3.3.4 List常用函数与方法
    • 3.4 Tuple(元组)
      • 3.4.1 tuple的声明
      • 3.4.2 tuple的索引与切片
      • 3.4.3 tuple的常用函数
    • 3.5 Set(集合)
      • 3.5.1 set的声明
      • 3.5.2 set不可以索引与切片
      • 3.5.3 set的运算
    • 3.6 字典
      • 3.6.1 字典的创建
      • 3.6.2 字典值的访问
      • 3.6.3 字典的keys()方法与values()方法
      • 3.6.4 字典的键只能是不可变数据类型
    • 3.7 稍复杂数据结构的使用与访问
  • 4. Python条件控制
    • 4.1 单分支if语句

      • 4.1.1 单分支if语句流程图
      • 4.1.2 单分支if语句语法格式
      • 4.1.3 单分支if语句例子
    • 4.2 双分支if语句
      • 4.2.1 双分支if语句流程图
      • 4.2.2 双分支if语句语法格式
      • 4.2.3 双分支if语句例子
    • 4.3 if嵌套
      • 4.3.1 if嵌套的流程图
      • 4.3.2 if嵌套的语法格式
  • 5. Python循环控制
    • 5.0 引子
    • 5.1 While循环
      • 5.1.1 基本语法结构
      • 5.1.2 while循环嵌套
      • 5.1.3 while嵌套循环的实例
      • 5.1.4 条件语句的一些特殊说明
      • 5.1.5 while循环中的continue和break语句
      • 5.1.6 while循环与else语句配合使用
    • 5.2 for循环
      • 5.2.1 for循环的一般格式
      • 5.2.2 for循环的continue与break语句
      • 5.2.3 for与else语句
    • 5.3 range函数
    • 5.4 课堂练习
  • 6. Python的各种导出式
    • 6.1 列表导出式
    • 6.2 字典导出式
    • 6.3 集合导出式
    • 6.4 元组导出式
  • 7.异常处理
    • 7.1 异常处理方法
    • 7.2 主动抛出异常
  • 8. 函数
    • 8.1 基本语法
    • 8.2 函数的参数
      • 8.2.1 必需参数
      • 8.2.2 关键字参数
      • 8.2.3 默认参数
      • 8.2.4 不定长参数
      • 8.2.5 输出参数
    • 8.3 匿名函数
    • 8.4 几个特殊函数:map(),filter(), reduce()
      • 8.4.1 遍历函数map()
      • 8.4.2 筛选函数filter()
      • 8.4.3 累计函数reduce()

本文的jupyter notebook脚本文件等从 百度网盘下载

0. Jupyter Notebook简介

0.1 Jupyter Notebook简介及启动

0.1.1 Jupyter Notebook简介

Jupyter Notebook是基于网页的用于交互计算的应用程序。其可被应用于全过程计算:开发、文档编写、运行代码和展示结果。
Jupyter Notebook是以网页的形式打开,可以在网页页面中直接编写代码和运行代码,代码的运行结果也会直接在代码块下显示。如在编程过程中需要编写说明文档,可在同一个页面中直接编写,便于作及时的说明和解释。

a = 1
b = 2
print(a+b)

0.1.2 Jupyter Notebook安装与启动

安装

  • 随anaconda安装
  • 单独安装
pip install jupyter

0.2 Jupyter Notebook里面的最常用的操作:

0.2.1 更改文件名

File–>Rename

0.2.2 模式切换

当前cell侧边为蓝色时,表示此时为命令模式,按Enter切换为编辑模式
当前cell侧边为绿色时,表示此时为编辑模式,按Esc切换为命令模式

0.2.3 命令模式快捷键

  • Y:把当前cell内容转换为代码形式

  • M:把当前cell内容转换为markdown形式

  • Ctrl+Enter:运行当前cell

  • Shift+Enter:运行当前cell并跳转到下一cell

  • Alt+Enter:运行当前cell并在下方新建cell

  • Tab:缩进

  • Shift+Table:减少缩进

  • A:在上方新建cell

  • B:在下方新建cell

  • 双击D:删除当前cell

0.2.4 查询帮助

help(print)
print?

help(print)
Help on built-in function print in module builtins:print(...)print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default.Optional keyword arguments:file:  a file-like object (stream); defaults to the current sys.stdout.sep:   string inserted between values, default a space.end:   string appended after the last value, default a newline.flush: whether to forcibly flush the stream.
print("abc",end="*")
print("def")
abc*def
print?

1. Python基础语法

1.1 编码

默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。
当然你也可以为源码文件指定不同的编码:

# -*- coding: gbk -*-

上述定义允许在源文件中使用 Windows中的简体中文字符编码,对应适合语言为非unicode的简体中文。

1.2 标识符

  • 只能由字母、数字或下划线组成
  • 只能由字母或下划线开头
  • 严格区分大小写
  • 不能够用保留字
  • 提倡用驼峰命名法命名
  • 标识符命名应做到见名知意
True
int32, true, 40XL,__name__, self
#  小驼峰
studentName = "RJG"
#  大驼峰
StudentName = "RJG"
a1 = 1
a_1 = 2
_a1 = 3
1a = 4
  File "<ipython-input-19-11c9e5e22322>", line 41a = 4^
SyntaxError: invalid syntax
import keyword
keyword.kwlist
['False','None','True','and','as','assert','async','await','break','class','continue','def','del','elif','else','except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or','pass','raise','return','try','while','with','yield']
and=1
  File "<ipython-input-22-1d82dc2ad2a5>", line 1and=1^
SyntaxError: invalid syntax
And=1

1.3 注释

  • python中单行注释以#开头
  • 多行注释可以每行用#,也可以用"““注释内容””",‘’’ ‘’’
"""python中单行注释以#开头
多行注释可以每行用#,也可以用'''注释内容'''
"""
# a是第一个输入
a= input("输入第一个参数:")
print(a)
输入第一个参数:a
a

1.4 行与缩进

python最具特色的就是使用缩进来表示代码块,不需要使用大括号 {}
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。
实例如下:

实例

if True:print("True")
else:print("False")

以下代码最后一行语句缩进数的空格数不一致,会导致运行错误:

if True:print("Answer")print("True")
else:print("Answer")print("False")# 缩进不一致,会导致运行错误
if True:print("True1")print("True2")
else:print("False1")print("False2")print("这是后续语句1")
print("这是后续语句2")
True1
True2
这是后续语句1
这是后续语句2

1.5 多行语句

Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠\来实现多行语句,例如:

total = item_one + \item_two + \item_three

[]{},或()中的多行语句,不需要使用反斜杠\,例如:

total = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five']

1.6 多个变量赋值

Python允许你同时为多个变量赋值。例如:

a = b = c = 1

以上实例,创建一个整型对象,值为 1,三个变量都指向同一个内存位置。
您也可以为多个对象指定多个变量。例如:

a, b, c = 1, 2, "PythonTest"

以上实例,两个整型对象 1 和 2 的分配给变量 a 和 b,字符串对象 “PythonTest” 分配给变量 c。

aa = bb = cc = 33
bb
33
a = 1
type(a)
int
b = 1.5
type(b)
float
b = 3
type(b)
int
a,b,c,d = 1,1.5,"abc",True
a
1
b
1.5
a,b=b,a
a
1.5
b
1
c
'abc'
d
True
type(c)
str
type(a)
int
type(d)
bool
a

1.7 输入输出

  • 控制台输入 input

    • 接收到的输入为字符串类型,若需数值类型参与运算,需对接收到的结果采用int、float等强制转换
    • 采用input(“…”)增加输入提示
  • 控制台打印输出 print

    • print默认输出是换行,如果要实现不换行则需要在输入参数中增加end=“”
    • print的格式化输出:
      • A. print(“num:%d” %num)
      • B. print(“num:{}”.format(num))
      • C. print(f"num:{num}")
m=10
n = int(input())
123
m+n
133
type(n)
int
name
'RJG'
name = input("姓名:")
姓名:rjg
name
'rjg'
num = 5.555
print("num:",num)
num: 5.555
print("num: %.2f" %num)
num: 5.55
num = 5
print("num:%d" %num)
num:5
print("num:{}".format(num))
num:5
print(f"num:{num}")
num:5

1.8 包的导入

  • import 包的名称
  • import 包的名称 as 包的别名
  • from 包的名称 import 模块的名称
  • from 包的名称 import 模块的名称 as 模块的别名
import os
os.getcwd()
'D:\\01130'
import numpy as np
np.
from matplotlib import pyplot
pyplot.plot()
from matplotlib import pyplot as plt

1.9 pip

  • 在线安装方式

    • pip install 包的名称 (这种是从pypi这个服务器上下载)
    • pip install 包的名称 -i http://mirrors.aliyun.com/pypi/simple/
  • 在线安装方式

pip install numpy #在线安装numpy,从pypi服务器上下载
pip install scrapy -i http://mirrors.aliyun.com/pypi/simple/ #在线安装scrapy,从后面指定源

  • 离线安装方式
    先下载.whl文件

pip install xxxxx.whl

  • 安装jupyter notebook自动目录生成插件

https://www.cnblogs.com/xiaoniu-666/p/10973911.html
主要三步:

  1. pip install jupyter_contrib_nbextensions -i https://pypi.mirrors.ustc.edu.cn/simple/ --trusted-host https://pypi.mirrors.ustc.edu.cn/
  2. jupyter contrib nbextension install --user --skip-running-check
  3. 取消最上面的的"disable。。。"前面的复选框,勾选下面的"Table of Contents(2)“前面的复选框”
  • pip国内的一些镜像
      阿里云 http://mirrors.aliyun.com/pypi/simple/
      豆瓣(douban) http://pypi.douban.com/simple/
      清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
      中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/

  • 修改源方法:

临时使用:
可以在使用pip的时候在后面加上-i参数,指定pip源
eg: pip install scrapy -i https://pypi.tuna.tsinghua.edu.cn/simple

2. Python运算符

  • 算术运算符
  • 比较算术符
  • 赋值运算符
  • 位运算符
  • 成员运算符
  • 身份运算符
  • 运算符优先级

2.1 算术运算符

  • +,-,*,**, /,// ,%
  • 特别需要注意的是:
    • /与//
    • %
    • **
5/2
2.5
5//2
2
8//3
2
13%3
1
13//3
4
13-3*(13//3)
1
2**4
16

2.2 比较(关系)运算符

  • >,<,==,>=,<=,!=
  • 需要注意的是:
    • 相等的判断:==而不是=(赋值)
    • 不相等的符号:!= ,不是~=,><
3>2
True
3==2
False
3>=2
True
3!=2
True
3>'3'
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-46-c7bc7547e6e5> in <module>
----> 1 3>'3'TypeError: '>' not supported between instances of 'int' and 'str'

2.3 赋值运算符

  • =, +=, -=,*=,/=,//=,%=
  • python中没有没有自增"++“或自减”–"
a = 3
a += 1 # a = a+1
a
4
a -=2
a
2

2.4 逻辑运算

  • 与(and)、或(or),非(not)
b
a = 2
b = 1
c = 3
(a ==1) and (b == 2) and (c == 3)
False
a = 1
b = 1
(a ==1) or (b == 2)
True
not(a==1)
False

2.5 位运算

  • &,|, ~,- ,<<,>>

2.6 成员运算符

  • in,not in
a = "abcd"
b = "b"b in a
True
a = [11,12,13,14]
b = 13
b in a
True
stuNames = {"张三","李四","王五"}
stuN = "张三3"
stuN in stuNames
False
if stuN in stuNames:print("请输入密码:")
else:print("你还没注册")
你还没注册

2.7 身份运算符

  • is,is not
a = 20
b = 20a is b
True
b = 30
a is b
False
id(a)
8791380370416
id(b)
8791380370736
a is not b
True
id(a)
8791380370416

id(b)
8791380370416

2.8 运算符优先级

详见: https://www.runoob.com/python3/python3-basic-operators.html#ysf8
建议用圆括号改变运算顺序

3. Python数据类型

  • Python3中的标准数据类型:

    • Number(数字)
    • String (字符串)
    • List (列表)
    • Tuple(元组)
    • Set(集合)
    • Dictionary(字典)
  • 可分为两大类:

    • 不可变数据类型(3个): Number、String、Tuple
    • 可变数据类型(3个):List、Dictionary、Set

    不可变数据类型: 当该数据类型的对应变量的值发生了改变,那么它对应的内存地址也会发生改变,对于这种数据类型,就称不可变数据类型。

    可变数据类型 :当该数据类型的对应变量的值发生了改变,那么它对应的内存地址不发生改变,对于这种数据类型,就称可变数据类型。

  • 另外一种分法:

    • 有序的:String,Tuple,List,Dictionary(3.6版本之后是有序的)。有序才可索引与切片
    • 无序的:Set,Dictionary(3.6之前是无序的)
alist = [1,2,3]
alist[1]
2
alist[1]=22
astr = "abcd"
astr[1]
'b'
astr[1]='e'
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-4-6b094b783159> in <module>
----> 1 astr[1]='e'TypeError: 'str' object does not support item assignment

aList = [1,2,3]
id(aList)
166826632
aList[1] = 200
aList
[1, 200, 3]
id(aList)
166826632

3.1 Number(数字)

3.1.1 包括的类型

Python3支持intfloatboolcomplex(复数)

var11,var12 = 1,True
del var11,var12
var1 = 1
var2 = 10
print(var1)
1
del var1
print(var1)
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-79-b5880a42db53> in <module>
----> 1 print(var1)NameError: name 'var1' is not defined

3.1.2 数值运算

  • 包括: +,-,*,/,**,%,//
  • 在混合运算时,Python会把整型转换位浮点型
 1 + 1.5
2.5
import math
math.ceil(1.3)
2
math.floor(1.9)
1

3.1.3 数字类型转换

  • int(x) 将x转换为整型
  • float(x) 将x转换为浮点型
  • complex(x) 将x转换为复数,实部是x,虚部是0
  • complex(x,y) 将转换为一个复数,实部是x,虚部是y
a = input("num:")
num:1.23
a
'1.23'
float(a)
1.23
int(1.23)
1

3.1.4 数值型相关的函数

详见 : https://www.runoob.com/python3/python3-number.html


3.2 String(字符串)

字符串在python中是用一对双引号(“”)或一对单引号(‘’)括起来的。

print( "What's your name?" )
What's your name?

3.2.1 字符串的索引

  • 索引值从左向右为从0开始逐渐递增
  • 索引值从右向左为从-1开始逐渐递减
  • 可通过 变量名[索引值] 获取到字符串该索引位置的字母
aStr = "abcdef"
aStr
'abcdef'
aStr[0]
'a'
aStr[2]
'c'
aStr[-1]
'f'
aStr[-2]
'e'

3.2.2 字符串的切片

  • 切片的表示:

    • 变量名 [起始索引:终止索引] 起始间所有元素切片
    • 变量名 [起始索引:终止索引:步长] 起始间按步长进行元素切片
    • 索引区间是左闭右开的(能取到左边索引的元素,取不到右边的)
aStr
'abcdef'
aStr[1:4]
'bcd'
aStr[1:4:]
'bcd'
aStr[1:4:1]
'bcd'
aStr[:4]
'abcd'
aStr[2:]
'cdef'
aStr[4]
'e'
aStr[1:4:2]
'bd'
aStr[-1]
'f'
aStr[-1:-4]
''
aStr[-1:-4:-1]
'fed'
bStr = "abcdefgh"
bStr[::-1]
'hgfedcba'
bStr[-1::-2]
'hfdb'

3.2.3 字符串的操作符

  • "+"运算是进行字符串连接
  • "*n"运算是字符串重复n次
  • in,not in : 成员运算
  • r/R : 原生字符串
  • % :格式化字符串
print("hello\n world!")
helloworld!
print("hello\\n world!")
hello\n world!
print(r"hello\n world!")
hello\n world!
1+2
3
aStr
'abcdef'
bStr
'abcdefgh'
aStr + bStr
'abcdefabcdefgh'

"我错了 "*100
'我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 我错了 '
'A' in "ABC"
True
'A' not in "abc"
True
print("hello \n world!")
hello world!
print(r"hello \n world!")
hello \n world!
"%s ,I love you" %("CQTBI")
'CQTBI ,I love you'
a = 3.1415926
b = 1.57
"%.2f + %.2f=%.1f" %(a,b,a+b)
'3.14 + 1.57=4.7'

3.2.4 字符串函数

  • str.capitalize(),str.lower(),str.upper(),str.title()
  • str.strip(),str.lstrip(),str.rstrip(),str.replace()
  • str.split()

    1. str.capitalize(),str.lower(),str.upper(),str.title()
s = "hello world. chong qing."
s.capitalize()
'Hello world. chong qing.'
s.title()
'Hello World. Chong Qing.'
s1 = s.upper()
s1
'HELLO WORLD. CHONG QING.'
s1.lower()
'hello world. chong qing.'
    1. strip()/lstrip()/rstrip()/replace()
a1 = input("input a num:")
input a num:1234
a1
'1234'
a2 = input("input a num:")
input a num:   1234
a2
'   1234    '
a1==a2
False
a1.strip()==a2.strip()
True
s = "hello world!world!world!"
s.replace("world","cqtbi")
'hello cqtbi!cqtbi!cqtbi!'

3.3 List(列表)

3.3.1 list的声明

  • alist = [1,2,3]
  • alist = list()
  • alist = []
alist = [1,2,3,1.5,"abc",True]
type(alist)
list
blist = []
blist
[]
blist[0] = 1
blist
---------------------------------------------------------------------------IndexError                                Traceback (most recent call last)<ipython-input-61-884767279b48> in <module>
----> 1 blist[0] = 12 blistIndexError: list assignment index out of range
clist = list()
clist
[]
clist.append(3)

3.3.2 list的索引与切片

list也是一种序列,索引与切片与string

a = [1,2,3,4,5]
a[0]
1
a[-1]
5
a[5]
---------------------------------------------------------------------------IndexError                                Traceback (most recent call last)<ipython-input-64-4a84d856522b> in <module>
----> 1 a[5]IndexError: list index out of range
a[1:4:2]
[2, 4]

3.3.3 List运算符

  • “+”: List连接
  • “*”: List重复
  • in/not in: 成员运算
a
[1, 2, 3, 4, 5]
a+a
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
a*2
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
a*3
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
3 in a
True

3.3.4 List常用函数与方法

  • .append(x), .extend(L),.insert(i,x)
  • .pop(i), .remove(x), .clear()
  • .count(x),.index(x)
  • .sort(),.reverse()

    1. .append(x), .extend(L),.insert(i,x)
alist = []
alist[0]=2
---------------------------------------------------------------------------IndexError                                Traceback (most recent call last)<ipython-input-73-fab289a1af31> in <module>
----> 1 alist[0]=2IndexError: list assignment index out of range
alist.append(2)
alist
[2]
alist.append(4)
alist
[2, 4]
alist.insert(1,3)
alist
[2, 3, 4]
blist = [11,12,13]
alist.append(blist)
alist
[2, 3, 4, [11, 12, 13]]
len(alist)
4
alist[3][1]
12
alist2 = [2,3,4]
blist  = [11,12,13]
alist2.extend(blist)
alist2
[2, 3, 4, 11, 12, 13]
alist2.insert(3,blist)
alist2
[2, 3, 4, [11, 12, 13], 11, 12, 13]
scoreList = [11,22,89,95,63,45,56]
# list1 = [] # >=60
list1,list2= list(),list()
# list2 = []  # <60
for score in scoreList:if score >= 60:list1.append(score)print(score,'>=60!')else:list2.append(score)print(score,'<60!')print(">=60:")
print(list1)
print("<60:")
print(list2)
11 <60!
22 <60!
89 >=60!
95 >=60!
63 >=60!
45 <60!
56 <60!
>=60:
[89, 95, 63]
<60:
[11, 22, 45, 56]
list1
[89, 95, 63]
list2
[11, 22, 45, 56]
    1. .pop(i), .remove(x), .clear()
list2
[11, 22, 45, 56]
list2.pop(1)
22
list2
[11, 45, 56]
list2.pop()
56
list2
[11, 45]
if len(list2)>0:num = list2.pop()print(num)
alist= [1,2,4,"abc",11,5]
while len(alist)>0:num = alist.pop()print(num)
5
11
abc
4
2
1
list1
[89, 95, 63]
list1.remove(95)
list1
[89, 63]

    1. .count(x),.index(x)
a = [11,22,333,11,2,11,333]
a.count(11)
3
aStr.count('a')
3
a[1]
22
a.index(22)
1
a.index(333)
2
    1. .sort(),.reverse()
a
[11, 22, 333, 11, 2, 11, 333]
a.sort()
a
[2, 11, 11, 11, 22, 333, 333]
a = [11,22,333,11,2,11,333]
a.sort(reverse = True)
a
[333, 333, 22, 11, 11, 11, 2]
a = [11,22,333,11,2,11,333]
a.reverse()
a
[333, 11, 2, 11, 333, 22, 11]
a = [11,22,333,11,2,11,333]
a[::-1]
[333, 11, 2, 11, 333, 22, 11]

alist = [1]
type(alist)
list
import random
random.randint(0,100)
8
alist = [1,2,5,3,111,12]
alist.sort()
alist
[1, 2, 3, 5, 12, 111]
alist = [1,2,5,3,111,12]
sorted(alist)
[1, 2, 3, 5, 12, 111]
alist
[1, 2, 5, 3, 111, 12]

3.4 Tuple(元组)

3.4.1 tuple的声明

  • atuple = (1,2,3)
  • atuple = ()
  • atuple = tuple()
  • 一个元素的tuple:atuple=(1,)
atuple = (1,2,3)
type(atuple)
tuple
btuple = (1,1.5,"abc",True)
btuple
(1, 1.5, 'abc', True)
ctuple = ()
type(ctuple)
tuple
dtuple = tuple()
type(dtuple)
tuple
atuple = (2)
type(atuple)
int
atuple = (2,)
type(atuple)
tuple
atuple
(2,)

3.4.2 tuple的索引与切片

与前面讲的序列数据结构string、list类似

btuple = (1,1.5,"abc",True)
btuple[2]
'abc'
btuple[1:3]
(1.5, 'abc')

3.4.3 tuple的常用函数

  • .count(x):统计x的个数
  • .index(x):找到x出现的第一次的位置
btuple = (1,1.5,"abc",True,1.5,2,1.5)
btuple.count(1.5)
3
btuple.index('abc')
2
alist =[1,1.5,"abc",True,1.5,2,1.5]
alist[1] = 15
alist
[1, 15, 'abc', True, 1.5, 2, 1.5]
btuple
(1, 1.5, 'abc', True, 1.5, 2, 1.5)
btuple[1]
1.5
btuple[1]=15
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-157-92314aae2fb9> in <module>
----> 1 btuple[1]=15TypeError: 'tuple' object does not support item assignment
astr = "abcdef"
astr[1]='B'
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-160-bcc7726d56b8> in <module>1 astr = "abcdef"
----> 2 astr[1]='B'TypeError: 'str' object does not support item assignment
btuple = (1,[1.5,2],"abc",True,1.5,2,1.5)
btuple
(1, [1.5, 2], 'abc', True, 1.5, 2, 1.5)
len(btuple)
7
btuple[0]=10
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-164-a81dd0a9a1b3> in <module>
----> 1 btuple[0]=10TypeError: 'tuple' object does not support item assignment
btuple[1][0]=15
btuple
(1, [15, 2], 'abc', True, 1.5, 2, 1.5)

3.5 Set(集合)

3.5.1 set的声明

  • aSet = {1,2,3}
  • aSet = set()
aSet = {}
type(aSet)
dict
aSet = set()
type(aSet)
set
aSet = {1}
type(aSet)
set
aSet = {1,2,4}
aSet
{1, 2, 4}
type(aSet)
set
aSet[0]
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-170-a255b6ebc78f> in <module>
----> 1 aSet[0]TypeError: 'set' object is not subscriptable
aSet = {1,2,4,1,2,5,7}
aSet
{1, 2, 4, 5, 7}
aList = [1,2,4,1,2,5,7]
aList
[1, 2, 4, 1, 2, 5, 7]
aSet= set(aList)
aSet
{1, 2, 4, 5, 7}
cList = list(aSet)
cList
[1, 2, 4, 5, 7]
a = 44
a in aSet
False

3.5.2 set不可以索引与切片

要获取集合内元素一般用遍历集合的方法

aSet[0]
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-33-a255b6ebc78f> in <module>
----> 1 aSet[0]TypeError: 'set' object is not subscriptable
aSet = {1,2,4,1,2,5,7}
for item in aSet:print(item)
1
2
4
5
7

3.5.3 set的运算

  • 成员运算:in/ not in
  • 集合特有的运算:&,|,^,-
a = set("sabcdef")
b = set("efghi")
print(a)
print(b)
{'b', 'd', 'f', 'c', 'a', 'e', 's'}
{'g', 'f', 'i', 'h', 'e'}
a&b # 交集
{'e', 'f'}
a|b # 并集
{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 's'}
a^b # a与b中不同时存在的
{'a', 'b', 'c', 'd', 'g', 'h', 'i', 's'}
b^a
{'a', 'b', 'c', 'd', 'g', 'h', 'i', 's'}
a -b #a中存在而b中不存在的
{'a', 'b', 'c', 'd', 's'}
b - a #b中存在而a中不存在的
{'g', 'h', 'i'}
b = set()
# b = {1}
type(b)
set
a = {}
type(a)
dict

3.6 字典

字典是用{}括起来的一系列的键(key):值(value)对。

adict = {"name":"RJG","age":43}
adict
{'name': 'RJG', 'age': 43}
type(adict)
dict
adict["name"]
'RJG'
adict["age"]
43
adict.keys()
dict_keys(['name', 'age'])
adict.values()
dict_values(['RJG', 43])
for key in adict.keys():print("key:",key)print("value:",adict[key])
key: name
value: RJG
key: age
value: 43

3.6.1 字典的创建

  • 空字典的创建
emptyDict1 = {}
emptyDict2 = dict()
emptyDict2
{}
  • 创建的同时初始化
aDict = {"name":"RJG","age":43}
bDict = {(0,0):"RJG","H":43}
bDict
{(0, 0): 'RJG', 'H': 43}
dDict = {1:"RJG",2:43}
dDict
{1: 'RJG', 2: 43}
cDict = {[0,0]:"RJG","H":43}
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-64-915017c8f386> in <module>
----> 1 cDict = {[0,0]:"RJG","H":43}TypeError: unhashable type: 'list'
  • 利用关键字dict以及key参数方式创建
aDict = dict(name="RJG",age=43)
aDict
{'name': 'RJG', 'age': 43}
  • 利用二元组列表的方式创建
listA = [("name","RJG"),("age",43),("性别","男")]
type(listA)
list
listA
[('name', 'RJG'), ('age', 43), ('性别', '男')]
listA[1]
('age', 43)
type(listA[1])
tuple
listA[1][0]
'age'
aDict = dict(listA)
aDict
{'name': 'RJG', 'age': 43, '性别': '男'}

3.6.2 字典值的访问

  • 自接利用key索引
aDict["性别"]
'男'
  • 利用.get()方法
aDict.get("性别")
'男'

3.6.3 字典的keys()方法与values()方法

aDict
{'name': 'RJG', 'age': 43, '性别': '男'}
aDict.keys()
dict_keys(['name', 'age', '性别'])
aDict.values()
dict_values(['RJG', 43, '男'])
for key in aDict.keys():#print("%s:%s" %(key, aDict[key]))#print(f"{key}:{aDict[key]}")print("{}:{}".format(key,aDict[key]))
name:RJG
age:43
性别:男

3.6.4 字典的键只能是不可变数据类型

所以键的类型可以是 数字,字符串或者元组
不可以是列表,集合与字典。

# 键可以是数字
dict1 = {1:"a",2:"abc",3:"d"}
dict1
{1: 'a', 2: 'abc', 3: 'd'}
# 键可以是字符
dict2 = {"name":"张三丰","age":108,"sex":"男"}
dict2
{'name': '张三丰', 'age': 108, 'sex': '男'}
# 键可以是元组
dict3 = {(0, 0.0): 0.0,(1, 1.5): 3.25,(2, 3.0): 13.0,(3, 4.5): 29.25,(4, 6.0): 52.0}
dict3
{(0, 0.0): 0.0,(1, 1.5): 3.25,(2, 3.0): 13.0,(3, 4.5): 29.25,(4, 6.0): 52.0}
# 键不可以是列表
dict4 = {[0, 0.0]: 0.0,[1, 1.5]: 3.25,[2, 3.0]: 13.0,[3, 4.5]: 29.25,[4, 6.0]: 52.0}
dict4
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-6-6fdd9b0a344b> in <module>4          [2, 3.0]: 13.0,5          [3, 4.5]: 29.25,
----> 6          [4, 6.0]: 52.0}7 dict4TypeError: unhashable type: 'list'
# 键不可以是集合
dict5 = {{0, 0.0}: 0.0,{1, 1.5}: 3.25,{2, 3.0}: 13.0,{3, 4.5}: 29.25,{4, 6.0}: 52.0}
dict5
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-7-0b795b1f1a53> in <module>4          {2, 3.0}: 13.0,5          {3, 4.5}: 29.25,
----> 6          {4, 6.0}: 52.0}7 dict5TypeError: unhashable type: 'set'
# 键不可以是字典
dict6 = {{0: 0.0}: 0.0,{1: 1.5}: 3.25,{2: 3.0}: 13.0,{3: 4.5}: 29.25,{4: 6.0}: 52.0}
dict6
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-8-ffa7b60b94a2> in <module>4          {2: 3.0}: 13.0,5          {3: 4.5}: 29.25,
----> 6          {4: 6.0}: 52.0}7 dict6TypeError: unhashable type: 'dict'

3.7 稍复杂数据结构的使用与访问

classInfo = {"001":{"name":"stu1","sex":"F","age":18,"score":{"English":85,"math":90,"python":100}},"002":{"name":"stu2","sex":"F","age":18,"score":{"English":56,"math":60,"python":70}},"003":{"name":"stu3","sex":"m","age":19,"score":{"English":76,"math":70,"python":80}}
}
classInfo
{'001': {'name': 'stu1','sex': 'F','age': 18,'score': {'English': 85, 'math': 90, 'python': 100}},'002': {'name': 'stu2','sex': 'F','age': 18,'score': {'English': 56, 'math': 60, 'python': 70}},'003': {'name': 'stu3','sex': 'm','age': 19,'score': {'English': 76, 'math': 70, 'python': 80}}}

classInfo["002"]
{'name': 'stu2','sex': 'F','age': 18,'score': {'English': 56, 'math': 60, 'python': 70}}
classInfo["002"]["score"]
{'English': 56, 'math': 60, 'python': 70}
classInfo["002"]["score"]["English"]
56
classInfo2 = [["001",{"name":"stu1","sex":"F","age":18,"score":{"English":85,"math":90,"python":100}}],["002",{"name":"stu2","sex":"F","age":18,"score":{"English":56,"math":60,"python":70}}],["003",{"name":"stu3","sex":"m","age":19,"score":{"English":76,"math":70,"python":80}}]]
for stu in classInfo2:# print(stu[1])#print(stu[1]['name'])print(stu[1]['name'],":",stu[1]['score']['English'])
stu1 : 85
stu2 : 56
stu3 : 76
classInfo2
[['001',{'name': 'stu1','sex': 'F','age': 18,'score': {'English': 85, 'math': 90, 'python': 100}}],['002',{'name': 'stu2','sex': 'F','age': 18,'score': {'English': 56, 'math': 60, 'python': 70}}],['003',{'name': 'stu3','sex': 'm','age': 19,'score': {'English': 76, 'math': 70, 'python': 80}}]]
classInfo2[1]
['002',{'name': 'stu2','sex': 'F','age': 18,'score': {'English': 56, 'math': 60, 'python': 70}}]
classInfo2[1][1]
{'name': 'stu2','sex': 'F','age': 18,'score': {'English': 56, 'math': 60, 'python': 70}}
type(classInfo2[1][1])
dict
classInfo2[1][1]['score']
{'English': 56, 'math': 60, 'python': 70}
classInfo2[1][1]['score']['math']
60
reText = '{"jwotestProduct":null,"score":0,"comments":[{"id":17053509798,"guid":"1c86c08d4ab286ed66f30815578e70d2","content":"外形外观:精美\n屏幕音效:保真\n拍照效果:图像清晰,防抖,很不错。\n运行速度:运行流畅,响应迅速。\n待机时间:像我这样机不离手的人,待机时长12个小时,很不错了。","vcontent":"{$%&外形外观:&%$}精美\n{$%&屏幕音效:&%$}保真\n{$%&拍照效果:&%$}图像清晰,防抖,很不错。\n{$%&运行速度:&%$}运行流畅,响应迅速。\n{$%&待机时间:&%$}像我这样机不离手的人,待机时长12个小时,很不错了。","creationTime":"2022-01-26 10:47:12","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"usefulVoteCount":1,"userClient":4,"anonymousFlag":1,"plusAvailable":201,"mobileVersion":"10.3.4","productColor":"亮黑色","productSize":"5G版8GB+256GB(华为原装66W充电套装)","textIntegral":20,"status":1,"referenceId":"10040676733526","referenceTime":"2021-12-18 18:36:04","nickname":"编***7","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":20,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":39,"afterDays":0},{"id":16938956213,"guid":"e059e2618fb6fe5e9f30b15a7d97c72c","content":"手感特别好,\n外形外观:好\n运行速度:好\n屏幕音效:好","vcontent":"手感特别好,\n{$%&外形外观:&%$}好\n{$%&运行速度:&%$}好\n{$%&屏幕音效:&%$}好","creationTime":"2022-01-04 12:56:20","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":0,"userClient":4,"discussionId":1025789791,"imageCount":3,"anonymousFlag":1,"plusAvailable":0,"mobileVersion":"10.3.0","images":[{"id":1655077581,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/218770/23/9859/185111/61d3d371Ebf43b349/edf61d5ddb537aa2.jpg","imgTitle":"","status":0},{"id":1655077582,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/108887/13/21546/244415/61d3d372E11869612/c5d1b800f5b3a8c4.jpg","imgTitle":"","status":0},{"id":1655077583,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/104135/36/21022/228931/61d3d373E13ee0082/dde007721e849c7a.jpg","imgTitle":"","status":0}],"mergeOrderStatus":2,"productColor":"亮黑色","productSize":"5G版8GB+256GB(华为原装66W充电套装)","textIntegral":20,"imageIntegral":20,"status":1,"referenceId":"10023409497119","referenceTime":"2022-01-01 11:20:15","nickname":"****b","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":40,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":3,"afterDays":0},{"id":15422475971,"guid":"8459320c2f9dc454432d138eb3f17c24","content":"手机很好看,充电速度很快,待机时间也长,卖家服务态度很好,很耐心,物流速度也快,很满意","creationTime":"2021-03-15 12:06:02","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replies":[],"replyCount":1,"score":5,"imageStatus":1,"usefulVoteCount":1,"userClient":4,"discussionId":878599255,"imageCount":3,"anonymousFlag":1,"plusAvailable":0,"mobileVersion":"","images":[{"id":1384840834,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/169663/34/12561/276916/604edd28Edf951247/b65a70981099530f.jpg","imgTitle":"","status":0},{"id":1384840835,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/161569/36/12763/181007/604edd28E8291544f/0f90794acca50fdb.jpg","imgTitle":"","status":0},{"id":1384840836,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/157925/25/13938/225009/604edd29E6211d032/6349f3a5722f3b09.jpg","imgTitle":"","status":0}],"videos":[{"id":1384840837,"mainUrl":"https://jvod.300hu.com/img/2021/65510732/1/img2.jpg","videoHeight":1280,"videoWidth":960,"videoLength":15,"videoTitle":"","videoUrl":547149406,"videoId":547149406,"status":0,"remark":"https://jvod.300hu.com/vod/product/22bf7c74-ff05-4a98-9ae9-ef6418bb881f/4a99b034159f4799aadf30cc6aaa60df.mp4?source=2&h265=h265/18799/ab2fcb95f558443c95c7ba176e75859a.mp4"}],"mergeOrderStatus":2,"productColor":"夏日胡杨","productSize":"全网通8GB+128GB(12期免息)","textIntegral":20,"imageIntegral":20,"status":1,"referenceId":"10026333731563","referenceTime":"2021-03-12 10:37:06","nickname":"****b","replyCount2":1,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":40,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":3,"afterDays":0},{"id":16989089516,"guid":"4b59973b26dac2e585ad9b72bf1cfdd1","content":"手机今天收到了,算是过年的?了,感觉很不错,把旧手机的资料和应用都克隆到华为mate40上,这么多app,用起来一点不卡,很流畅,强烈推荐,支持国货,支持华为!","creationTime":"2022-01-14 16:21:21","isDelete":false,"isTop":false,"userImageUrl":"storage.360buyimg.com/i.imageUpload/5a4d454e323330303231343537303138373839383731_sma.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":2,"userClient":4,"discussionId":1031218017,"imageCount":2,"anonymousFlag":1,"plusAvailable":103,"mobileVersion":"10.3.3","images":[{"id":1665044487,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/148090/37/21858/70735/61e1327eE7b567025/fde21c679e9cb27e.jpg","imgTitle":"","status":0},{"id":1665044489,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/149227/29/22928/97553/61e13280Eafacac79/2581c8624ad6f8fe.jpg","imgTitle":"","status":0}],"mergeOrderStatus":2,"productColor":"亮黑色","productSize":"5G版8GB+256GB(华为原装66W充电套装)","textIntegral":20,"imageIntegral":20,"status":1,"referenceId":"10023409497119","referenceTime":"2022-01-06 13:03:36","nickname":"Z***2","replyCount2":0,"userImage":"storage.360buyimg.com/i.imageUpload/5a4d454e323330303231343537303138373839383731_sma.jpg","orderId":0,"integral":40,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":8,"afterDays":0},{"id":15455363897,"guid":"18356d7334ce0801714100af926389cb","content":"很喜欢,现在优惠,一直想买,店家服务好,态度好,关键是现在的国产产品要比国外实惠好用,功能多,最主要质量好,希望所有人喜欢。","creationTime":"2021-03-24 08:01:42","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":3,"userClient":4,"discussionId":882575564,"imageCount":3,"anonymousFlag":0,"plusAvailable":0,"mobileVersion":"","images":[{"id":1392088055,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/169636/6/14538/243215/605a8163Ed54e2d4d/ece23e0044fdf1f4.jpg","imgTitle":"","status":0},{"id":1392088056,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/167607/4/15367/177825/605a8165E6296e9c3/91634e402a17a0f3.jpg","imgTitle":"","status":0},{"id":1392088057,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/158683/15/15242/216941/605a8165Eec99041c/23d2fd6d4bb9b8fc.jpg","imgTitle":"","status":0}],"videos":[{"id":1392088058,"mainUrl":"https://jvod.300hu.com/img/2021/67103174/1/img2.jpg","videoHeight":1280,"videoWidth":724,"videoLength":15,"videoTitle":"","videoUrl":549928001,"videoId":549928001,"status":0,"remark":"https://jvod.300hu.com/vod/product/6e27b0ae-034a-49d5-bd2f-a43dce240a2a/9ae40fe6a576448eb2a70ddfa636ed21.mp4?source=2&h265=h265/18799/930ed9f63f13407bb328fecff490731c.mp4"}],"mergeOrderStatus":2,"productColor":"亮黑色","productSize":"全网通8GB+256GB(碎屏险无线充套装)","textIntegral":40,"imageIntegral":40,"status":1,"referenceId":"10023409497116","referenceTime":"2021-03-19 22:13:42","nickname":"****B","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":80,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":"Aq181GAS2Kqc73rgal_jVxuS6SjYrNe37GL8Eaz9hc3uiobJc-1IS9Y0Drmp_UhSU3pVZT8ZPifznsj1QoAQGg","days":5,"afterDays":0},{"id":16986127684,"guid":"82ec20c84dea511c04024f1ace7e2faf","content":"感觉还不如用了两年的MATE30快呢,不会是翻新机吧","creationTime":"2022-01-13 21:46:17","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replies":[{"id":973492454,"commentId":16986127684,"content":"尊敬的客户,您好,很抱歉给您带来不好的体验,本店品牌授权店铺 所售都是全新未拆封的新机,保障国行正品,支持专柜验货, 支持全国联保,享受三包服务,质保期为:一年质保 如因质量问题或故障,凭厂商维修中心或特约维修点的质量检测证明,享受7日内退货,15日内换货,15日以上在质保期内享受免费保修等三包服务 ,如您使用有任何疑问都可以联系在线客服给您处理, 祝您生活愉快!","pin":"京***雪","userClient":98,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","ip":"36.161.109.62","productId":10023409497116,"replyList":[],"nickname":"京***雪","creationTime":"2022-01-13 21:57:45","parentId":0,"targetId":0,"venderShopInfo":{"id":10065765,"appName":"//xinjinghe.jd.com","title":"京合旗舰店","venderId":10201627}}],"replyCount":1,"score":1,"usefulVoteCount":4,"userClient":4,"anonymousFlag":1,"plusAvailable":201,"mobileVersion":"9.1.2","productColor":"亮黑色","productSize":"4G版8GB+256GB(有充)","textIntegral":20,"status":1,"referenceId":"10023409497116","referenceTime":"2022-01-08 20:01:23","nickname":"天***云","replyCount2":1,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":20,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":5,"afterDays":0},{"id":16073363851,"guid":"ce88d9d21d72045d067af82cbb23a5dc","content":"手机收到,外观高大上,触屏灵敏,其他待进一步使用反馈效果。期待赠品快快到来!","creationTime":"2021-08-02 12:33:31","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":0,"userClient":21,"discussionId":944855796,"imageCount":3,"anonymousFlag":1,"plusAvailable":0,"mobileVersion":"","images":[{"id":1506011993,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/187352/22/16204/108993/61077535Ef320bd61/f505612aaf774ee9.jpg","imgTitle":"","status":0},{"id":1506011994,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/180939/16/17279/168862/61077539E1cb41a5c/d067948e613d2019.jpg","imgTitle":"","status":0},{"id":1506011995,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/176901/18/17148/141960/6107753dEbf0e0319/47d7f1f01fd1db9e.jpg","imgTitle":"","status":0}],"mergeOrderStatus":2,"productColor":"秘银色","productSize":"5G版8GB+256GB(12期免息)","textIntegral":20,"imageIntegral":20,"status":1,"referenceId":"10026333731560","referenceTime":"2021-07-30 08:38:06","nickname":"e***9","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":40,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":3,"afterDays":0},{"id":16008465813,"guid":"eb23a6afbf5c2fd5d0c6d33a27518f75","content":"今天收到的,在上班晚上回去再研究研究,物流很快,商家服务也很好。","creationTime":"2021-07-19 17:10:54","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":1,"userClient":4,"discussionId":938863193,"imageCount":8,"anonymousFlag":1,"plusAvailable":103,"mobileVersion":"10.0.8","images":[{"id":1494933519,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/174032/16/20299/71270/60f54199E30a2ffaa/3e75526b5f65c8d6.jpg","imgTitle":"","status":0},{"id":1494933520,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/196687/37/13750/60846/60f5419aE78e96068/1a8594f1c77ee9be.jpg","imgTitle":"","status":0},{"id":1494933881,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/182283/29/14680/65194/60f5419aE2c5fbb50/5985da45a62be499.jpg","imgTitle":"","status":0},{"id":1494933882,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/190504/7/13705/63813/60f5419bE02c10e0f/a8f8dabfa28e59d1.jpg","imgTitle":"","status":0},{"id":1494933883,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/173521/22/20254/72033/60f5419cE0ef23c54/674fdaae5efb4550.jpg","imgTitle":"","status":0},{"id":1494933884,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/178281/37/14896/193390/60f5419cEaf6c1667/3ca9a14a83b8302a.jpg","imgTitle":"","status":0},{"id":1494933885,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/175783/40/20236/80216/60f5419dEb2339f33/e7a142cf50232f1e.jpg","imgTitle":"","status":0},{"id":1494933886,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/191776/27/13503/73628/60f5419dE7bf4ddbb/8172f04dd4c37d7c.jpg","imgTitle":"","status":0}],"mergeOrderStatus":2,"productColor":"亮黑色","productSize":"5G版8GB+128GB","textIntegral":20,"imageIntegral":20,"status":1,"referenceId":"10023409497118","referenceTime":"2021-07-17 08:40:23","nickname":"****f","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":40,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":2,"afterDays":0},{"id":16962463968,"guid":"d53c7e5811c127d8c7bf7da792e136ed","content":"非常喜欢?外观漂亮,用起来速度快,功能强大,华为质量我信赖。另外,表扬店铺,送了不少东西,我都喜欢","creationTime":"2022-01-08 23:25:03","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":0,"userClient":4,"discussionId":1028203687,"imageCount":2,"anonymousFlag":1,"plusAvailable":203,"mobileVersion":"10.3.2","images":[{"id":1659523279,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/125078/4/21467/207384/61d9acceE1c2f5bf5/41d4f5a1a0887b88.jpg","imgTitle":"","status":0},{"id":1659523280,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/109537/3/22039/138301/61d9acceE98d9b7bd/0dec6077d76fc126.jpg","imgTitle":"","status":0}],"mergeOrderStatus":2,"productColor":"亮黑色","productSize":"5G版8GB+256GB(华为原装66W充电套装)","textIntegral":40,"imageIntegral":40,"status":1,"referenceId":"10023409497119","referenceTime":"2021-12-26 21:32:56","nickname":"****2","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":80,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":13,"afterDays":0},{"id":16901620684,"guid":"ace981772a59d7b604024f1ace7e2faf","content":"我在京东京合旗舰店购买的华为Mate40Pro手机,是顺丰快运送来的,从合肥到长沙手机仅36小时便到手上,第二天赠品也到手,第四天,电子发票也到手上 ,完全出乎预料 ,包装完好,快递神速,完全符合店家的承诺 ,谢谢,十分感谢!","creationTime":"2021-12-29 18:12:49","isDelete":false,"isTop":false,"userImageUrl":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","topped":0,"replyCount":0,"score":5,"imageStatus":1,"usefulVoteCount":0,"userClient":4,"discussionId":1023035309,"imageCount":2,"anonymousFlag":1,"plusAvailable":0,"mobileVersion":"10.2.4","images":[{"id":1650063474,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/163993/2/24550/116511/61cc349fEdea90607/99684f3bbc31056a.jpg","imgTitle":"","status":0},{"id":1650063475,"imgUrl":"//img30.360buyimg.com/n0/s128x96_jfs/t1/138745/12/26479/94016/61cc34a1Ec0d2ddf4/30972e8c53b8e35c.jpg","imgTitle":"","status":0}],"mergeOrderStatus":2,"productColor":"亮黑色","productSize":"5G版8GB+256GB(华为原装66W充电套装)","textIntegral":20,"imageIntegral":20,"status":1,"referenceId":"10023409497119","referenceTime":"2021-12-24 16:05:16","nickname":"u***j","replyCount2":0,"userImage":"misc.360buyimg.com/user/myjd-2015/css/i/peisong.jpg","orderId":0,"integral":40,"productSales":"[]","referenceImage":"jfs/t1/109310/36/23875/117632/62208a0fEc5d8c3fd/3d27cbc4586e26d9.jpg","referenceName":"华为Mate40 Pro手机5G/4G可选 麒麟9000【支持鸿蒙HarmonyOS】 亮黑色 5G版 8GB+256GB","firstCategory":9987,"secondCategory":653,"thirdCategory":655,"aesPin":null,"days":5,"afterDays":0}],"soType":5,"csv":"eid=100^^tagid=ALL^^pid=20001^^sku=10020432669647^^sversion=1001^^pageSize=2","imageListCount":441,"hotCommentTagStatistics":[{"id":"2b480964d06f7f9c","name":"流畅至极","count":1,"type":4,"canBeFiltered":true,"stand":1,"rid":"2b480964d06f7f9c","ckeKeyWordBury":"eid=104^^tagid=2b480964d06f7f9c^^pid=20001^^sku=10040676733526^^sversion=1000^^token=20c273bf44105dad"},{"id":"621a1c388cce99d3","name":"清晰度高","count":1,"type":4,"canBeFiltered":true,"stand":1,"rid":"621a1c388cce99d3","ckeKeyWordBury":"eid=104^^tagid=621a1c388cce99d3^^pid=20001^^sku=10040676733526^^sversion=1000^^token=e8728e1414bb8217"},{"id":"3b0e2360369520ea","name":"声音清晰","count":1,"type":4,"canBeFiltered":true,"stand":1,"rid":"3b0e2360369520ea","ckeKeyWordBury":"eid=104^^tagid=3b0e2360369520ea^^pid=20001^^sku=10040676733526^^sversion=1000^^token=31f51c60737b018a"},{"id":"6c35b8cf25810e3c","name":"操作简单","count":1,"type":4,"canBeFiltered":true,"stand":1,"rid":"6c35b8cf25810e3c","ckeKeyWordBury":"eid=104^^tagid=6c35b8cf25810e3c^^pid=20001^^sku=10040676733526^^sversion=1000^^token=55f7cfc4fea3ba1b"}],"testId":"cmt","vTagStatistics":null,"maxPage":29,"productCommentSummary":{"skuId":10040676733526,"averageScore":5,"defaultGoodCount":0,"defaultGoodCountStr":"2000+","commentCount":0,"commentCountStr":"2000+","goodCount":0,"goodCountStr":"600+","goodRate":0.97,"goodRateShow":97,"generalCount":0,"generalCountStr":"6","generalRate":0.009,"generalRateShow":1,"poorCount":0,"poorCountStr":"10+","poorRate":0.021,"poorRateShow":2,"videoCount":0,"videoCountStr":"20+","afterCount":0,"afterCountStr":"30+","showCount":0,"showCountStr":"100+","oneYear":0,"sensitiveBook":0,"fixCount":0,"plusCount":0,"plusCountStr":"0","buyerShow":0,"poorRateStyle":4,"generalRateStyle":1,"goodRateStyle":145,"installRate":0,"productId":10040676733526,"score1Count":13,"score2Count":2,"score3Count":4,"score4Count":12,"score5Count":614}'
 bytes1 = reText.encode("GBK")
re = bytes1.decode("utf8")
---------------------------------------------------------------------------UnicodeDecodeError                        Traceback (most recent call last)<ipython-input-112-8bd338f474c7> in <module>
----> 1 re = bytes1.decode("utf8")UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd in position 116: invalid continuation byte

4. Python条件控制

Python条件控制语句是通过一条或多条语句的执行结果(True或者False)来决定后面的代码块是否执行。

4.1 单分支if语句

4.1.1 单分支if语句流程图

4.1.2 单分支if语句语法格式

if 条件语句:语句1语句2
语句3

执行过程:

  1. 条件语句结果为True,则执行语句1,语句2等构成的语句块,再执行后面的顺序语句3等;
  2. 条件语句结果为False,则跳过语句1,语句2等构成的语句块,直接执行后面的顺序语句3等;

注意点

  • 1.条件语句后用冒号
  • 2.每个语句块内部的语句须采用相同的缩进

4.1.3 单分支if语句例子

练习: 输入一个整数,若能被5整除,则该数增加3,并打印增加后的结果。

aInput = int(input("请输入一个整数:"))
if aInput%5==0:aInput += 3print(aInput)

4.2 双分支if语句

4.2.1 双分支if语句流程图

4.2.2 双分支if语句语法格式

if 条件语句:语句1语句2
else:语句3语句4
语句5

执行过程:

  1. 条件语句结果为True,则执行语句1,语句2等构成的语句块,跳过后面的else语句块(包括语句3,语句4等构成的语句块),再执行后面的顺序语句5等;
  2. 条件语句结果为False,则跳过语句1,语句2等构成的if语句块,直接执行后面的顺序语句3,语句4等构成的else语句块,再执行最后的顺序语句5

注意点

  • 1.条件语句后用冒号
  • 2.每个语句块内部的语句须采用相同的缩进
  • 3.else后面不能够跟条件语句,直接用冒号
var1 = 100
if var1 == 100:print("var1 是100!")
else:print("var1 不是100!")
print("判断结束")
var1 是100!
判断结束

4.2.3 双分支if语句例子

var = 100
if var == 100:b = var+100print("var is 100!")
else:print("var is not 100!")
var is 100!

4.3 if嵌套

4.3.1 if嵌套的流程图

4.3.2 if嵌套的语法格式

  • 第一种语法格式
if 条件语句1:[语句块1]  # 条件语句1为真则执行if 条件语句2:语句块2 #条件语句1为真,且条件语句2也为真才执行else:语句块3 #条件语句1为真,且条件语句2为假才执行else:  #条件语句1为假执行[语句块4]  # 条件语句1为假则执行if 条件语句3:语句块5 #条件语句1为假,且条件语句3为真才执行else:语句块6 #条件语句1为假,且条件语句3为假才执行   

  • 第二种语法格式
if 条件语句1:语句块1  # 条件语句1为真则执行elif 条件语句2:语句块2 #条件语句1为假,且条件语句2为真才执行
elif 条件语句3:语句块3 #条件语句1为假,条件语句2为假,且条件语句3为真才执行
else:语句块4 #条件语句1/条件语句2/条件语句3都为假,才执行   

等价于:

if 条件语句1:语句块1  # 条件语句1为真则执行
else:  #条件语句1为假执行    if 条件语句2:语句块2 #条件语句1为假,且条件语句2为真才执行else:if 条件语句3:语句块3 #条件语句1为假,条件语句2为假,且条件语句3为真才执行else:语句块4 #条件语句1/条件语句2/条件语句3都为假,才执行   
var = 50
if var == 100:b = var+100print("var is 100!")
elif var==50:print("var is 50!")
else:print("var is not 100, and var is not 50!")
var is 50!

注意点:

  1. 条件表达式后面要用":";
  2. 各个语句块内部需采用相同的缩进;
  3. else后面不能够跟条件表达式,直接用“:”
  4. 多分支时后面的条件判断用"elif",不是"elseif".

课堂练习
要求从键盘输入一个整数,判断其与2和3的整除关系,并将整除关系打印输出。
即:
A. 能同时被2和3整除;
B.
C.
D.

  • 一种方案
var1 = int(input("请输入一个整数:"))
if var1 % 2 ==0:# 能被2整除if var1 % 3 == 0:# 能被3整除print("能同时被2和3整除!")else:# 不能被3整除print("能被2整除不能被3整除!")
else:# 不能被2整除if var1 % 3 == 0:# 能被3整除print("能被3整除不能被2整除!")else:# 不能被3整除print("2和3都不整除该数!")
请输入一个整数:7
2和3都不整除该数!
  • 另一种方案
var1 = int(input("请输入一个整数:"))
if (var1 % 2 ==0) and (var1 %3 == 0):print("能同时被2和3整除!")
elif (var1 % 2 ==0) and (var1 %3 != 0):print("能被2整除不能被3整除!")
elif (var1 % 2 !=0) and (var1 %3 == 0):print("能被3整除不能被2整除!")
else:print("2和3都不整除该数!")

练习2:
求解一元二次方程的 ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0,从键盘输入a,b,c,然后求解出其实数解输出。

根据中学知识,一元二次方程的实数解分以下几种情况:
Δ=b2−4ac\Delta = b^2-4acΔ=b2−4ac

  1. $\Delta < 0 $ 无实数解

  2. $\Delta = 0 $ 两个相同的实数解

    x1=x2=−b2ax_1 = x_2 = \frac{-b}{2a}x1​=x2​=2a−b​

  3. $\Delta > 0 $ 两个不同的实数解:

    1) x1=−b+Δ2ax_1 = \frac{-b+\sqrt{\Delta}}{2a}x1​=2a−b+Δ​​
    2) x2=−b−Δ2ax_2 = \frac{-b-\sqrt{\Delta}}{2a}x2​=2a−b−Δ​​

#输入参数a,b,c
a = float(input("请输入a:"))
b = float(input("请输入b:"))
c = float(input("请输入c:"))   #计算delta
delta = b*b - 4*a*c
print("delta判别式为:",delta)# 根据delta判断方程实数解的情况
if delta <0:print("此方程无实数解。")
elif delta == 0:x = -b/(2*a)print("此方程有两个相同的实数根,其值为:%f" %x)
else:x1 = (-b+delta**0.5)/(2*a)x2 = (-b-delta**0.5)/(2*a)print("此方程有两个不同的实数根")print("x1=",x1)print("x2=",x2)

5. Python循环控制

5.0 引子

  • Python循环控制的结构
    循环语句就是在符合条件的情况下,从夫执行一个代码块。
    Python循环语句有while循环和for循环,其结构流程图如下:

5.1 While循环

while循环和if语句一样,也有条件表达式。
与if语句不同的是,如果条件为真,则一直执行while后面的语句块,直到条件表达式为假。

5.1.1 基本语法结构

循环控制变量初始化语句
while 条件表达式:语句1...语句n循环控制变量更新语句跳出while之后的语句
n = 1
while n <= 10:print(n)print("I LOVE CQTBI!")    n += 1 print(n)
1
I LOVE CQTBI!
2
I LOVE CQTBI!
3
I LOVE CQTBI!
4
I LOVE CQTBI!
5
I LOVE CQTBI!
6
I LOVE CQTBI!
7
I LOVE CQTBI!
8
I LOVE CQTBI!
9
I LOVE CQTBI!
10
I LOVE CQTBI!
11

练习
用while循环,求出1+2+…+ 100的和。

mysum = 0
n = 1
while n<=100:mysum += nn += 1 print(mysum)
5050

自主练习
用while循环,求出1-100之间能被3整除的数之和。

mysum = 0
n = 1
while n<=100 :if n%3 == 0:mysum += n        n += 1 print(mysum)

5.1.2 while循环嵌套

while循环嵌套的流程图

当两个或者多个循环结构相互嵌套式,位于外层的循环结构称为外循环,位于内层的循环结构称为内循环。
循环嵌套结构代码的执行,Python解释器执行流程为:

  1. 当外循环条件为True时,这执行外循环中的循环体;
  2. 外循环包含了普通语句与内循环,当内循环条件为True时,会执行内循环的循环体,直到内循环的条件为False,跳出内循环。
  3. 如果此时外循环条件仍然为True,则返回到第2步,继续执行外循环体,直到外循环的条件为False。
  4. 当内循环的条件为False,且外循环为False,则整个循环才算执行完毕。
del n
m = 0
n = 0
while m<5:
#     n = 0 while n<3:print(f"m:{m}, n:{n}")n += 1print(m)m += 1 print("finished!")
m:0, n:0
m:0, n:1
m:0, n:2
0
1
2
3
4
finished!
n
3

语法结构

while 外循环条件表达式:外循环体的常规语句(一般还包括内循环控制变量的初始化)while 内循环条件表达式:内循环的循环体....内循环的控制变量的自增外循环体的常规语句外循环的控制变量的自增整个循环执行完之后的顺序语句

5.1.3 while嵌套循环的实例

i = 0
while i<5:print(f"外循环的第{i}次")m = 0while m <4:print(f"内循环的第{m}次")m += 1print("="*20)i+=1
外循环的第0次
内循环的第0次
内循环的第1次
内循环的第2次
内循环的第3次
====================
外循环的第1次
内循环的第0次
内循环的第1次
内循环的第2次
内循环的第3次
====================
外循环的第2次
内循环的第0次
内循环的第1次
内循环的第2次
内循环的第3次
====================
外循环的第3次
内循环的第0次
内循环的第1次
内循环的第2次
内循环的第3次
====================
外循环的第4次
内循环的第0次
内循环的第1次
内循环的第2次
内循环的第3次
====================
i = 0
m = 0
while i<5:print(f"外循环的第{i}次")while m <4:print(f"内循环的第{m}次")m += 1print("="*20)i+=1
外循环的第0次
内循环的第0次
内循环的第1次
内循环的第2次
内循环的第3次
====================
外循环的第1次
====================
外循环的第2次
====================
外循环的第3次
====================
外循环的第4次
====================

练习
采用循环嵌套语句打印输出如下三角形:

*
* *
* * *
* * * *
* * * * *
i = 0
while i<5:# print(f"外循环的第{i}次")m = 0while m <= i:print("* ",end = "")m += 1print(" ") i+=1
*
* *
* * *
* * * *
* * * * *

例3
在上例的基础上,打印输出如下的九九乘法表:

1 * 1 =  1
2 * 1 =  2   2 * 2 =  4
3 * 1 =  3   3 * 2 =  6   3 * 3 =  9
4 * 1 =  4   4 * 2 =  8   4 * 3 = 12   4 * 4 = 16
5 * 1 =  5   5 * 2 = 10   5 * 3 = 15   5 * 4 = 20   5 * 5 = 25
6 * 1 =  6   6 * 2 = 12   6 * 3 = 18   6 * 4 = 24   6 * 5 = 30   6 * 6 = 36
7 * 1 =  7   7 * 2 = 14   7 * 3 = 21   7 * 4 = 28   7 * 5 = 35   7 * 6 = 42   7 * 7 = 49
8 * 1 =  8   8 * 2 = 16   8 * 3 = 24   8 * 4 = 32   8 * 5 = 40   8 * 6 = 48   8 * 7 = 56   8 * 8 = 64
9 * 1 =  9   9 * 2 = 18   9 * 3 = 27   9 * 4 = 36   9 * 5 = 45   9 * 6 = 54   9 * 7 = 63   9 * 8 = 72   9 * 9 = 81
i = 1
while i<=9:# print(f"外循环的第{i}次")m = 1while m <= i:print("%d * %d = %2d  " %(i, m, i*m),end = "")m += 1print(" ") i+=1
1 * 1 =  1
2 * 1 =  2  2 * 2 =  4
3 * 1 =  3  3 * 2 =  6  3 * 3 =  9
4 * 1 =  4  4 * 2 =  8  4 * 3 = 12  4 * 4 = 16
5 * 1 =  5  5 * 2 = 10  5 * 3 = 15  5 * 4 = 20  5 * 5 = 25
6 * 1 =  6  6 * 2 = 12  6 * 3 = 18  6 * 4 = 24  6 * 5 = 30  6 * 6 = 36
7 * 1 =  7  7 * 2 = 14  7 * 3 = 21  7 * 4 = 28  7 * 5 = 35  7 * 6 = 42  7 * 7 = 49
8 * 1 =  8  8 * 2 = 16  8 * 3 = 24  8 * 4 = 32  8 * 5 = 40  8 * 6 = 48  8 * 7 = 56  8 * 8 = 64
9 * 1 =  9  9 * 2 = 18  9 * 3 = 27  9 * 4 = 36  9 * 5 = 45  9 * 6 = 54  9 * 7 = 63  9 * 8 = 72  9 * 9 = 81

5.1.4 条件语句的一些特殊说明

在Python中:

  • 常数非零的情况下条件判断为True,0判断为False
  • 非空列表、集合等会被认为True,空的这些数据结构会被认为False

5.1.5 while循环中的continue和break语句

  • continue结束本次循环,开始下一次循环
  • break结束本层循环,跳出本层循环(若还有外循环,在进行外循环的相应操作
i = 1
while i<=9:# print(f"外循环的第{i}次")m = 1while m <= i:if m == 3:breakprint("%d * %d = %2d  " %(i, m, i*m),end = "")m += 1print(" ") i+=1
1 * 1 =  1
2 * 1 =  2  2 * 2 =  4
3 * 1 =  3  3 * 2 =  6
4 * 1 =  4  4 * 2 =  8
5 * 1 =  5  5 * 2 = 10
6 * 1 =  6  6 * 2 = 12
7 * 1 =  7  7 * 2 = 14
8 * 1 =  8  8 * 2 = 16
9 * 1 =  9  9 * 2 = 18

5.1.6 while循环与else语句配合使用

循环控制变量初始化语句
while 条件表达式:语句1...语句n循环控制变量更新语句
else:else语句块跳出while之后的语句

执行的流程:

  • 如果while后面的条件语句为False,则执行else语句块
    通常情况下,若循环体内语句没有break语句,在跳出循环时,条件表达式都是False,因此跳出循环体时会去执行else语句; 若遇到break语句跳出循环时,此时条件表达式一般都是True,因此不会执行else语句块。
i = 0
while i<5:print("i in while:",i)i +=1
else:print("i out of while:",i)
i in while: 0
i in while: 1
i in while: 2
i in while: 3
i in while: 4
i out of while: 5
i = 0
while i<5:print("i in while:",i)i +=1 if i == 3:break
else:print("i out of while:",i)
i in while: 0
i in while: 1
i in while: 2

5.2 for循环

5.2.1 for循环的一般格式

for 变量 in 序列:循环执行语句块
else:else语句块循环之后的顺序语句块
stuInfo = {"stuNo1":"01130","stuName":"RJG"}
stuInfo.keys()
dict_keys(['stuNo1', 'stuName'])
stuInfo = {"stuNo1":"01130","stuName":"RJG"}
for key in stuInfo.keys():print(key,":",stuInfo[key])
stuNo1 : 01130
stuName : RJG
aset = {1,3,5,7,9}
for item in aset:print(item)
1
3
5
7
9
astr = "PythonTest"
for char in astr:print(char)
else:print("finish")
P
y
t
h
o
n
T
e
s
t
finish

5.2.2 for循环的continue与break语句

  • continue结束本次循环,开始下一次循环
  • break结束本层循环,跳出本层循环(若还有外循环,在进行外循环的相应操作
for i in range(3):print("外循环i:",i)for j in range(5):if j == 2:continueprint("内循环j:",j)  print("="*20)
外循环i: 0
内循环j: 0
内循环j: 1
内循环j: 3
内循环j: 4
====================
外循环i: 1
内循环j: 0
内循环j: 1
内循环j: 3
内循环j: 4
====================
外循环i: 2
内循环j: 0
内循环j: 1
内循环j: 3
内循环j: 4
====================
for i in range(3):print("外循环i:",i)for j in range(5):if j == 2:breakprint("内循环j:",j)  print("="*20)
外循环i: 0
内循环j: 0
内循环j: 1
====================
外循环i: 1
内循环j: 0
内循环j: 1
====================
外循环i: 2
内循环j: 0
内循环j: 1
====================

5.2.3 for与else语句

astr = "PythonTest"
for char in astr:if char == "o":continueprint(char)
else:print("没有遇到break语句")
P
y
t
h
n
T
e
s
t
没有遇到break语句
astr = "PythonTest"
for char in astr:if char == "o":breakprint(char)
else:print("没有遇到break语句")
P
y
t
h

5.3 range函数

range()返回的是一个可迭代对象(不是列表类型).

  • 函数语法

    • range(start,stop,step)
  • 参数说明:
    • start:计数从start开始,默认是0开始,例如range(5)等价于range(0,5);
    • stop:计数到stop结束,但不包括stop,例如range(0,5)是(0,1,2,3,4)没有5.
    • step:步长,默认是1.
for i in range(1,11):print(i)
1
2
3
4
5
6
7
8
9
10

5.4 课堂练习

  • 例1:
    写一段代码,判断2-20以内的数是否是质数,若是质数,则打印输出"xxx是质数";否者,对该数进行因数分解,写为:“xxx = AA * BB”
for m in range(2,21):for n in range(2,m):if m%n == 0:print("%d = %d * %d" %(m,n,m/n))breakelse:print("%d是质数!" %m)
2是质数!
3是质数!
4 = 2 * 2
5是质数!
6 = 2 * 3
7是质数!
8 = 2 * 4
9 = 3 * 3
10 = 2 * 5
11是质数!
12 = 2 * 6
13是质数!
14 = 2 * 7
15 = 3 * 5
16 = 2 * 8
17是质数!
18 = 2 * 9
19是质数!
20 = 2 * 10

  • 例2
    循环遍历如下班级每个学生信息,并打印输出。
classInfo = {"001":{"name":"stu1","sex":"F","age":18,"score":{"English":85,"math":90,"python":100}},"002":{"name":"stu2","sex":"F","age":18,"score":{"English":56,"math":60,"python":70}},"003":{"name":"stu3","sex":"m","age":19,"score":{"English":76,"math":70,"python":80}}
}
classInfo = {"001":{"name":"stu1","sex":"F","age":18,"score":{"English":85,"math":90,"python":100}},"002":{"name":"stu2","sex":"F","age":18,"score":{"English":56,"math":60,"python":70}},"003":{"name":"stu3","sex":"m","age":19,"score":{"English":76,"math":70,"python":80}}
}
for stuNo in classInfo.keys():print("="*20)print("学号:",stuNo)stuInfo = classInfo[stuNo]for stuItem in stuInfo.keys():  stuItemValue = stuInfo[stuItem]if type(stuItemValue)!=dict:print(stuItem,":",stuItemValue)continuefor scoreItem in stuItemValue.keys():print(scoreItem,":",stuItemValue[scoreItem])
====================
学号: 001
name : stu1
sex : F
age : 18
English : 85
math : 90
python : 100
====================
学号: 002
name : stu2
sex : F
age : 18
English : 56
math : 60
python : 70
====================
学号: 003
name : stu3
sex : m
age : 19
English : 76
math : 70
python : 80

6. Python的各种导出式

6.1 列表导出式

基本格式

mylist = [out_exp_res for out_exp in input_list if 条件表达式]

说明

  • out_exp_res: 列表生成元素表达式,可以是带有返回值的函数
  • for out_exp in input_list:迭代input_list中的每一项,把out_exp代入到out_exp_res中去运算
  • if 条件表达式:是过滤条件,满足条件的才生成新的元素

例1:

# 用列表导出式生成一个列表[1,2,3,4,5,6,7,8,9]
list1 = [i for i in range(1,10)]
list1
[1, 2, 3, 4, 5, 6, 7, 8, 9]

例2:

# 用列表导出式生成一个列表[1,4,9,16,25,36,49,64,81]
list2 = [i*i for i in range(1,10)]
list2
[1, 4, 9, 16, 25, 36, 49, 64, 81]
# 用之前的方法生成
list3 = []
for i in range(1,10):temp = i * i list3.append(temp)
list3
[1, 4, 9, 16, 25, 36, 49, 64, 81]

例3:

# 用列表导出式生成一个列表[9,36,81]
list4 = [i*i for i in range(1,10) if i%3==0]
list4
[9, 36, 81]

aset = {78,97,11,12,89,60,55,48,67,99,67,35,41,52,78}
result = {}
list1 = []
list2 = []
list3 = []
for item in aset:if item %3 == 0:list1.append(item)elif item%3 ==1:list2.append(item)else:list3.append(item)result['k1'] = list1
result['k2'] = list2
result['k3'] = list3
result
{'k1': [99, 12, 78, 48, 60], 'k2': [97, 67, 52, 55], 'k3': [35, 41, 11, 89]}
aset = {78,97,11,12,89,60,55,48,67,99,67,35,41,52,78}
result1 = {}
result1['k1'] = [i for i in aset if i%3==0]
result1['k2'] = [i for i in aset if i%3==1]
result1['k3'] = [i for i in aset if i%3==2]
result1
{'k1': [99, 12, 78, 48, 60], 'k2': [97, 67, 52, 55], 'k3': [35, 41, 11, 89]}

6.2 字典导出式

基本格式

mydict = {key_out_exp_res: value_out_exp_res for out_exp in input_list if 条件表达式}

说明

  • key_out_exp_res: 字典键值生成表达式,可以是带有返回值的函数
  • value_out_exp_res:字典value值生成表达式,可以是带有返回值的函数
  • for out_exp in input_list:迭代input_list中的每一项,把out_exp代入到out_exp_res中去运算
  • if 条件表达式:是过滤条件,满足条件的才生成新的元素

例1:

# 用字典导出式生成一个字典:{1:1,2:4,3:9,4:16,5:25,6:36,7:49,8:64,9:81}
dict1 = { i:i**2 for i in range(1,10)}
dict1
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

例2: 带过滤条件

# 用字典导出式生成一个字典:{1:1,3:9,5:25,7:49,9:81}
dict2 = { i:i**2 for i in range(1,10) if i%2==1}
dict2
{1: 1, 3: 9, 5: 25, 7: 49, 9: 81}

例3:zip打包函数

strList = ["abc","hello","i love cqtbi"]
# {"abc":3,"hello":5,"i love cqtbi":}
dict3 = {item:len(item) for item in strList}
dict3
{'abc': 3, 'hello': 5, 'i love cqtbi': 12}
name = ["张三",  "李四",  "王五", "赵六"]
sign = ["白羊座","双鱼座","狮子座","处女座"]
name
['张三', '李四', '王五', '赵六']
sign
['白羊座', '双鱼座', '狮子座', '处女座']
# ('张三','白羊座')
for item in zip(name,sign):print(item)n,s = itemprint(n)print(s)
('张三', '白羊座')
张三
白羊座
('李四', '双鱼座')
李四
双鱼座
('王五', '狮子座')
王五
狮子座
('赵六', '处女座')
赵六
处女座
# ('张三','白羊座')
for n,s in zip(name,sign):print(n,":",s)
张三 : 白羊座
李四 : 双鱼座
王五 : 狮子座
赵六 : 处女座
name = ["张三",  "李四",  "王五", "赵六"]
sign = ["白羊座","双鱼座","狮子座","处女座"]
#{"张三":"白羊座","李四":"双鱼座",...}
dict4 = {n:s  for n,s in zip(name,sign)}
dict4
{'张三': '白羊座', '李四': '双鱼座', '王五': '狮子座', '赵六': '处女座'}

6.3 集合导出式

基本格式

myset = {out_exp_res for out_exp in input_list if 条件表达式}

说明

  • out_exp_res: 集合元素生成表达式,可以是带有返回值的函数
  • for out_exp in input_list:迭代input_list中的每一项,把out_exp代入到out_exp_res中去运算
  • if 条件表达式:是过滤条件,满足条件的才生成新的元素
x = [1,23,34,3,5]
#{下的每一项求一个平方,放入集合中}
set1 = {i**2  for i in x}
set1
{1, 9, 25, 529, 1156}

6.4 元组导出式

基本格式

mytuple = (out_exp_res for out_exp in input_list if 条件表达式)

说明

  • out_exp_res: 元组元素生成表达式,可以是带有返回值的函数
  • for out_exp in input_list:迭代input_list中的每一项,把out_exp代入到out_exp_res中去运算
  • if 条件表达式:是过滤条件,满足条件的才生成新的元素
x = [1,23,34,3,5]
#(对x的每一项求一个平方,放入元组中)
tuple1 = (i**2  for i in x)
tuple1
<generator object <genexpr> at 0x000001C3E610DDC8>
for a in tuple1:print(a)

7.异常处理

Python遇到错误后,会引发异常。
如果异常对象未被处理或捕获,则程序就会用所谓的回溯(Traceback,一种错误信息)来终止执行。

例:
下面要求输入一个整数,若我们输入的不是整数而是小数或者是字母,则会出现异常。

var1 = int(input("请输入一个整数:"))
if var1 % 2 ==0:# 能被2整除if var1 % 3 == 0:# 能被3整除print("能同时被2和3整除!")else:# 不能被3整除print("能被2整除不能被3整除!")
else:# 不能被2整除if var1 % 3 == 0:# 能被3整除print("能被3整除不能被2整除!")else:# 不能被3整除print("2和3都不整除该数!")
请输入一个整数:a1---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-7-14832d68068c> in <module>
----> 1 var1 = int(input("请输入一个整数:"))2 if var1 % 2 ==0:3     # 能被2整除4     if var1 % 3 == 0:5         # 能被3整除ValueError: invalid literal for int() with base 10: 'a1'

7.1 异常处理方法

try/except语句的一般格式:

try:<语句> #怀疑有可能发生异常的语句
except <异常类型1>[,异常参数名1]:<异常类型1的处理代码>
except <异常类型2>[,异常参数名2]:<异常类型2的处理代码>
except:<发生了异常,但异常类型未在前面列出的处理代码>
else:<没有发生异常时代码>
finally:<不管是否发生异常,最终都要执行的代码>

try:var1 = int(input("请输入一个整数:"))
except:print("您输入的不是一个整数! ")
else:    if var1 % 2 ==0:# 能被2整除if var1 % 3 == 0:# 能被3整除print("能同时被2和3整除!")else:# 不能被3整除print("能被2整除不能被3整除!")else:# 不能被2整除if var1 % 3 == 0:# 能被3整除print("能被3整除不能被2整除!")else:# 不能被3整除print("2和3都不整除该数!")
finally:print("程序执行完毕!")
请输入一个整数:5
2和3都不整除该数!
程序执行完毕!
while True:   try:var1 = int(input("请输入一个整数:"))except:print("s! \n 请重试!")else:break    if var1 % 2 ==0:# 能被2整除if var1 % 3 == 0:# 能被3整除print("能同时被2和3整除!")else:# 不能被3整除print("能被2整除不能被3整除!")
else:# 不能被2整除if var1 % 3 == 0:# 能被3整除print("能被3整除不能被2整除!")else:# 不能被3整除print("2和3都不整除该数!")print("程序执行完毕!")
请输入一个整数:1.5
您输入的不是一个整数! 请重试!
请输入一个整数:11
2和3都不整除该数!
程序执行完毕!

课堂实例:
某学科采用百分制(成绩范围在[0,100],且可能有0.5分存在)。
请写一段脚本程序实现 根据键盘输入成绩,输出其等级,即:A:[90,100],B:[80,90),C:[70,80),D;[60,70),E[0,60)

while True:try:inputStr = input("请输入分数[0-100]:")score = float(inputStr)except :print("您输入的不是数字!\n请重试! ")else:breakif score >=90:print("A")
elif score >= 80:print("B")
elif score>=70:print("C")
elif score>=60:print("D")
else:print("E")
while True:try:inputStr = input("请输入分数[0-100]:")score = float(inputStr)except :print("您输入的不是数字!\n请重试! ")else:breakif score>=0 and score<=100:if score >=90:print("A") elif score >= 80:print("B")elif score>=70:print("C")elif score>=60:print("D")else:print("E")
else:print("输入不是[0,100]范围内!")
请输入分数[0-100]:110
输入不是[0,100]范围内!
while True:try:inputStr = input("请输入分数[0-100]:")score = float(inputStr)except :print("您输入的不是数字!\n请重试! ")else:if score>=0 and score<=100:breakelse:print("输入不是[0,100]范围内!\n请重试! ")if score >=90:print("A")
elif score >= 80:print("B")
elif score>=70:print("C")
elif score>=60:print("D")
else:print("E")
请输入分数[0-100]:A
您输入的不是数字!
请重试!
请输入分数[0-100]:100.5
输入不是[0,100]范围内!
请重试!
请输入分数[0-100]:95.0
A

7.2 主动抛出异常

我们可以使用raise语句自己触发异常

raise语法格式如下:

raise [Exception [, args [, traceback]]]

语句中 Exception 是异常的类型(例如,NameError)参数标准异常中任一种,args 是自已提供的异常参数。

最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。

x = 10
if x>5:raise Exception('x 不能大于5。 此时x的值是:{}'.format(x))
---------------------------------------------------------------------------Exception                                 Traceback (most recent call last)<ipython-input-6-13b5e7d3eaa2> in <module>1 x = 102 if x>5:
----> 3     raise Exception('x 不能大于5。 此时x的值是:{}'.format(x))Exception: x 不能大于5。 此时x的值是:10

课堂实例:采用主动抛出异常
某学科采用百分制(成绩范围在[0,100],且可能有0.5分存在)。
请写一段脚本程序实现 根据键盘输入成绩,输出其等级,即:A:[90,100],B:[80,90),C:[70,80),D;[60,70),E[0,60)

while True:try:inputStr = input("请输入分数[0-100]:")score = float(inputStr)if score <0 or score>100:raise Exception("输入不是[0,100]范围内!\n请重试! ")break   except ValueError :print("您输入的不是数字!\n请重试! ")except Exception as e:print(f"{e}")if score >=90:print("A")
elif score >= 80:print("B")
elif score>=70:print("C")
elif score>=60:print("D")
else:print("E")
请输入分数[0-100]:110
输入不是[0,100]范围内!
请重试!
请输入分数[0-100]:100
A
float("1.5a")
---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-1-2e869456a8ab> in <module>
----> 1 float("1.5a")ValueError: could not convert string to float: '1.5a'

8. 函数

8.1 基本语法

  • 函数代码块以def关键字开头,后面接着跟函数的标识名和圆括号;
  • 任何传入参数必须放置圆括号中,用逗号隔开,圆括号内的这部分用于定义输入参数;
  • 函数的第一行语句可使用文档字符串存放函数说明;
  • 函数内容以圆括号后的冒号提示开始,需采用缩进;
  • return[表达式] 结束函数,返回一个或者多个值给调用方,不带表达式的return 相当于返回的是None
    即 Python定义函数的一般格式是:
def 函数名(输入参数1,输入参数2,...):函数体代码return 函数返回表达式

实例:

def hello1():"""hello1,input: Nonefunction: 打印输入hello!"""s = "Hello!"print(s)
help(hello1)
Help on function hello1 in module __main__:hello1()hello1,input: Nonefunction: 打印输入hello!
?hello1
hello1()
Hello!
help(hello1)
Help on function hello1 in module __main__:hello1()hello1,input: Nonefunction: 打印输入hello!

def hello2(name):s = "Hello,"+name+"!"print(s)
hello2("RJG")
Hello,RJG!
def myAdd(a,b):c = a+breturn c
a = 3
b = 5
c = myAdd(a,b)
c
8
a
3

8.2 函数的参数

以下是调用函数时可以使用的正式参数类型

  • 必需参数
  • 关键字参数
  • 默认参数
  • 不定长参数

8.2.1 必需参数

必需参数是指函数调用时,必须以与函数声明时一样的个数、顺序传入,否则就会出错。

def myFun(a,b):"求a的b次方"c = a**breturn c
myFun()
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-35-2d51ef0751d8> in <module>
----> 1 myFun()TypeError: myFun() missing 2 required positional arguments: 'a' and 'b'
myFun(2)
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-33-d75e1e032fa9> in <module>
----> 1 myFun(2)TypeError: myFun() missing 1 required positional argument: 'b'
# 2的3次方(8)
myFun(3,2) # 顺序不一致,结果错误
9

8.2.2 关键字参数

关键字参数就是指的函数调用时,指明实参传递到哪个形参上面去。
使用关键字参数允许函数调用时,参数的顺序与函数申明时不一样。

以上面的函数定义为例,使用关键字参数

# 2的3次方(8)
myFun(b=3,a=2) # 顺序不一致,结果正确
8

注意:形参名不能写错

# 2的3次方(8)
myFun(bb=3,a=2) # 顺序不一致,结果正确
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-40-f946965b831d> in <module>1 # 2的3次方(8)
----> 2 myFun(bb=3,a=2) # 顺序不一致,结果正确TypeError: myFun() got an unexpected keyword argument 'bb'

8.2.3 默认参数

调用函数时,如果没有传递参数,则会使用默认值。

def printInfo(name, age=18):print("姓名:", name)print("年龄:",age)return
printInfo("RJG",42)
姓名: RJG
年龄: 42
printInfo("RJG")
姓名: RJG
年龄: 18
help(print)
Help on built-in function print in module builtins:print(...)print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default.Optional keyword arguments:file:  a file-like object (stream); defaults to the current sys.stdout.sep:   string inserted between values, default a space.end:   string appended after the last value, default a newline.flush: whether to forcibly flush the stream.
print("a")
print("b")
a
b
print("a",end="\t")
print("b",end="\t")
a    b

8.2.4 不定长参数

函数调用时,可以传入任意个参数,这些参数叫不定长参数。
其基本语法结构如下:

def functionName([formal_args,] *var_args_tuple):functionBodyreturn [expression]

加了*的参数会以元组的形式传入函数体,存放所有未命名的变量参数。

# 打印输入的任意参数
def printInfo2(arg1, *vartuple):print("输出:")print(arg1)print(vartuple)
# 调用函数printInfo2
printInfo2(50,60)
输出:
50
(60,)
printInfo2(50,60,70)
输出:
50
(60, 70)

实例: 求2个或多个数之和

def addMulti(arg1,arg2, *vartuple):mysum = arg1+arg2for item in vartuple:mysum += itemreturn mysum
addMulti(10,20)
30
addMulti(10,20,30)
60
addMulti(10,20,30,40)
100

8.2.5 输出参数

- 没有return  #表示没有输出参数值,或者说输出为None
- return    #不带表达式,表示没有输出参数值,或者说输出为None
- return exp1 # 只输出一个参数
- return exp1,exp2[,exp3,]   #输出多个参数
# 无return语句
def hello1():"""hello1,input: Nonefunction: 打印输入hello!"""s = "Hello!"print(s)
a = hello1()
type(a)
Hello!NoneType
# 只有return,无表达式
def hello2():"""hello1,input: Nonefunction: 打印输入hello!"""s = "Hello!"print(s)return
b = hello2()
b
Hello!
type(b)
NoneType
# 带一个返回参数
def myAdd(a,b):c = a+breturn c
cc = myAdd(1,2)
cc
3
# 带多个返回参数
def myFun(a,b):c = a+bd = a*be = a**breturn c,d,e
# 调用带多个返回参数的一种方式
cc,dd,ee = myFun(1,2)
print("cc:",cc,"dd:",dd,"ee:",ee)
cc: 3 dd: 2 ee: 1
# 调用带多个返回参数的另一种方式
cde = myFun(1,2)
print("cde:",cde)
cde: (3, 2, 1)
cc,dd,ee,ff =  myFun(1,2)
cc,dd,ee,ff
---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)<ipython-input-80-206554acc494> in <module>
----> 1 cc,dd,ee,ff =  myFun(1,2)2 cc,dd,ee,ffValueError: not enough values to unpack (expected 4, got 3)

8.3 匿名函数

Python使用lambda来创建匿名函数。
所谓匿名,就是不使用def语句来定义一个函数。

  • lambda只是一个表达式,函数体一般比def定义的函数体简单;

基本语法:

lambda [arg1[,arg2,...argn]: expression``````python
# 标准定义
def myAdd(a,b):c = a+breturn c
# 标准定义
def myAdd(a,b):return a+b
# 标准定义的一种简写
def myAdd(a,b):return a+b
# 调用该函数:
mysum=myAdd(2,3)
#lambda表达式形式
sum2 = lambda a,b : a+b
# 调用lambda表达式
mysum2 = sum2(3,5)
mysum2
8

8.4 几个特殊函数:map(),filter(), reduce()

8.4.1 遍历函数map()

基本格式:

map(f,s)
  • f:函数
  • s:序列

map的作用就是对序列s中的每个元素执行相同的函数操作f,最终获取到一个新的序列 .

li = [11,22,33]
new_list = map(lambda a:a+100,li)
list(new_list)
[111, 122, 133]

8.4.2 筛选函数filter()

基本格式:

filter(f,s)
  • f:条件函数
  • s:序列

filter的作用就是将条件函数f作用到序列s上,最终获取到一个满足条件的新的序列

li = [11,22,33]
new_list = filter(lambda x:x>20,li)
list(new_list)
[22, 33]
li = [11,22,33,42]
new_list = filter(lambda x:x%3==0,li)
list(new_list)
[33, 42]

8.4.3 累计函数reduce()

基本格式:

reduce(function, sequence[, initial])

对参数序列中元素进行累计操作。

reduce有三个参数:

  • function:有两个参数的额函数, 必需参数
  • sequence: 元组、列表等可迭代对象, 必需参数
  • inital: 初始值, 可选参数

5、reduce的工作过程是:

在迭代sequence(tuple ,list ,dictionary, string等可迭代物)的过程中,

  • 首先把 前两个元素传给 函数参数,函数加工后,
  • 然后把得到的结果和第三个元素作为两个参数传给函数参数,
  • 函数加工后得到的结果又和第四个元素作为两个参数传给函数参数,依次类推

如果传入了 initial 值, 那么首先传的就不是 sequence 的第一个和第二个元素,而是 initial值和 第一个元素。

经过这样的累计计算之后合并序列到一个单一返回值

from functools import reducereduce(lambda x, y: x  + y, [11 , 22, 33, 44, 55])  # 11+22-->33 + 33 -->66 + 44 -->110 + 55 -->165
165
# 初始值100,100+11->111+22-->133+33-->166+44-->210+55-->265
reduce(lambda x, y: x  + y, [11 , 22, 33, 44, 55],100)
265

第1章 Python基础相关推荐

  1. 萌新向Python数据分析及数据挖掘 第一章 Python基础 第三节 列表简介 第四节 操作列表...

    第一章 Python基础 第三节 列表简介 列表是是处理一组有序项目的数据结构,即可以在一个列表中存储一个序列的项目.列表中的元素包括在方括号([])中,每个元素之间用逗号分割.列表是可变的数据类型, ...

  2. python是动态类型语言、变量不需要显示声明类型_【IT专家】第3章 Python基础

    第 3 章 Python 基础 2017/12/13 0 3-1 .标识符.为什么 python 中不需要变量名和变量类型声明? python 语言是动态的.强类型语言,一言以蔽之! 动态编译语言特点 ...

  3. python中 1.34e3_Python快速编程入门——第2章 Python基础语法

    第2章 python基础语法 一.基本语法 二.变量和数据类型 三.标识符和关键字 四.简单数值类型 一.基本语法 注释:Python的注释是用# 不像C/C++使用的是//或者/*/.多行注释好像挺 ...

  4. 廖雪峰python教程——第一章 Python基础

    第一章 Python基础 一.数据类型和变量 Python的数据类型包括整数.浮点数.字符串.布尔值.空值.变量.常量等.其中整数可以表示任意大小的整数:空值是Python里一个特殊的值,用None表 ...

  5. 【python第一章 基础捋顺,第二章 python基础语法】

    第一章 基础捋顺,第二章 python基础语法 第一章 基础捋顺 第二章 python基础语法 2.1输入输出 2.2代码注释 2.3代码缩进 2.4命名规范 2.5变量 2.6基本数据类型 2.7数 ...

  6. 第一章 Python基础 ——一起搬砖打地基

    目录 前言 第一章 Python基础 1.表达式 2.整型.浮点型和字符串数据类型 3.字符串的连接和复制 字符串的连接--"+"操作符 字符串的复制--" * &quo ...

  7. Python面试宝典(第二章 Python基础)

    Python面试宝典(第二章 Python基础) Python面试宝典(第二章 Python基础) 基础语法 输入输出 问题:代码中要修改不可变数据会出现什么问题? 抛出什么异常? 问题:a=1,b= ...

  8. 《Python编程快速上手——让繁琐工作自动化》——第一部分 Python编程基础 第1章 Python基础 1.1 在交互式环境中输入表达式...

    本节书摘来自异步社区<Python编程快速上手--让繁琐工作自动化>一书中的第1章,第1.1节,作者[美] Al Sweigart,王海鹏 译,更多章节内容可以访问云栖社区"异步 ...

  9. python 字典排序成绩_集体备课第四章 python基础与顺序结构

    第四章   第一节 python基础 填写上机记录:日期:9.28 班级:  节次:5     内容:python基础 下课时,整理好座椅后,再离开. 1.数据类型: 数字(整数(int).float ...

  10. p3.第一章 Python基础入门 -- Python编程基本概念 (三)

    1.2.2 Python语言 1.2.2.1 Python发展 1989年圣诞节期间,为了打发无聊的时间,荷兰人Guido van Rossum(吉多·范罗苏姆)(数学.计算机双硕士,2005年加入G ...

最新文章

  1. BUUCTF-[网鼎杯 2020 青龙组]singal——angr学习记录
  2. WInforn中设置ZedGraph的焦点显示坐标格式化以及显示三个坐标数的解决办法
  3. sql2012简体中文版安装
  4. python matplotlib画散点图_python matplotlib库绘制散点图例题解析
  5. C语言的inline
  6. 引用之函数返回值 函数的返回值为引用类型《三》
  7. SpanBERT: 抽取式问答的利器
  8. 彩色证件照片常用的红色、蓝色背景颜色值
  9. MSL、TTL、RTT
  10. 计算机界面视频录制软件,电脑版的录视频软件如何使用?录屏精灵为大家介绍基本操作...
  11. Python统计学01——数据可视化
  12. 古代益智游戏汉诺塔java解决
  13. 银行利率bp是什么意思,利率加点bp怎么计算
  14. HTML_canvas
  15. Whitelabel Error Page原因及解决方案
  16. 京东月薪45k的AI算法工程师,需要具备怎样的技能?
  17. 苹果微信多开_微信双开是什么?是不是需要两个手机号?
  18. android流程点击开机键熄屏,一种基于android系统的灭屏状态下指纹解锁加速亮屏方法与流程...
  19. 机器学习深度学习数据集大汇总
  20. jeremiah(jeremiah wright简介)

热门文章

  1. 用批处理的方式压缩文件
  2. 动态平衡网格交易_网格交易 套利:期货经典书籍
  3. ABAP 新特性 - CORRESPONDING
  4. Matlab自定义颜色图
  5. 读取HDF或者NetCDF格式的栅格数据
  6. 2750 心系南方灾区
  7. Unity高德定位获取天气预报
  8. mfs网络分布式文件系统、高可用、iscsi存储方式的mfs、fence
  9. MYSQL默认隔离级别详解
  10. FeignException$InternalServerError [500] during [POST]同时出现converter.HttpMessageConversionException