Python课堂笔记

1. 基础阶段
1.1 课程定位
( 1 )从行业角度来说:开发、网安、云原生、都会用到编程相关的技术
( 2 )从校招角度来说:所有 IT 岗位都会对学生编程能力进行考查
( 3 ) Python 相对而言比较简单,容易入手,比较好学
1.2 学习方法
( 1 )逢山开路,遇水架桥:学习编程的核心并不是仅局限于语法,而是在于如何利用语法去解决实际的
计算机问题
( 2 )观千剑而识器,操千曲而晓声:学习编程没有捷径,只有不停地多敲,多练,多解决问题,只有量
变才能质变
( 3 )应该将编程的学习当成一个长期的任务去执行
( 4 )前期的编码,禁止使用各种高级的编码软件( PyCharm , Eclpise ) , 必须要做到一点,一字一字地去敲代码
( 5 )推荐了两个题集,不要眼高手低
1.3 软件概述
软件的定义
是指一些按照特定顺序组织的能够被计算机识别的数据与指令的集合
在解决问题的时候,一定要先分析问题(把解决问题的步骤先一步一步列出来,然后再利用编程语言进
行编码)
软件的分类
操作系统软件: Windows Android IOS Harmony
主要负责管理和调控计算机硬件,给用户提供最基本的计算机功能(磁盘管理,上网管理,内存管理,
用户管理 ...... )
应用软件:微信 优酷 支付宝 网易云
提供专业领域服务的软件,是基于操作系统软件运行的
编程语言
机器语言:所有的数据都是由 0 和 1 组成,人看不懂,机器能看懂
汇编语言: 1 2 add ,必须要考虑计算机的执行过程,门槛比较高
高级语言: C C++ Java Python JavaScript.... ,以人类的角度设计的,对学习者非常友好,但是计算机就看不懂了
进阶知识:
静态编译型: C C++ Java
动态解释型: Python JavaScript (脚本语言) 编译与解释的区别:
静态与动态的区别:

静态对于变量有明确的类型定义的 动态对变量没有明确类型定义的
在 C C++ Java 中,基本数据类型变量(将常量数据存储在变量空间当中)
int a = 3 ;
int b = 4 ;
在 C C++ 中,指针变量(存储的是变量的物理内存地址)
int a = 3 ;
int* b ;
b = & a ;
int** c ;
c = & b ;
printf ( "%d" , & c ); //0x789
printf ( "%d" , * c ); //0x123
printf ( "%d" , &**& c ); //0x456

在 Java 中,引用数据类型变量(将对象在堆内存中的地址给变量)
Object obj = new Object ();
Object obj2 = obj ;

动态语言(所有的数据都是对象!所有的变量都是引用数据类型变量)
var a = 1
var b = 1.1
b = new object ();

1.4 安装环境
Python 开发工具包
http://python.p2hp.com/downloads/windows/index.html
如何验证安装成功: win+R 输入 cmd 打开控制台 输入 python 命令
如果没有出现 3.12.1 的提示,去找到 Python 的安装目录:
C:\Users\Administrator\AppData\Local\Programs\Python\Python312
我的电脑图标,邮件,属性,高级系统设置,环境变量, Path ,双击,新建,粘贴路径,确定,确定,
确定,重新打开 CMD 窗口测试
VSCode
https://code.visualstudio.com/
1.5 脚本与交互
交互模式
打开 CMD 窗口,输入 python 指令,进入到了 python 交互模式
print() 输出函数,输出的内容写在一对小括号中 print(XXX)
弊端:代码不能持久保存,代码随着窗口关闭而消失
C:\Users\Administrator>python
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
C:\Users\Administrator>python
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello Wolrd!")
Hello Wolrd!
>>> print(1 + 2)
3
我们一般在做简单的代码演示、测试会使用到交互模式
为了永久保存代码,需要脚本模式
脚本模式
打开 VSCode , File , New Folder ,选择代码目录, New File 按钮创建文件,输入名称和后缀名 (.py)
注意:一定要养成随时按 crtl+s 的习惯 保存
如何运行 Python 脚本文件呢
打开 CMD 窗口,进入到代码目录路径
指令: python XXX.py 运行 XXX.py 文件
1.6 基本数据
Python 能够操作的数据都有哪些
常量
不能够改变的量 - 字面量
整数常量
注意:没有 byte short long 之分 一律默认 int
小数常量
注意:没有 float 与 double 之分 默认 float
字符串常量
字符串表示一段文本信息,程序会将文本信息原封不动的处理
>>> print ( 10 ) # 十进制
10
>>> print ( 0b1001 ) # 二进制 binary
9
>>> print ( 0o12 ) # 八进制 Oct...
10
>>> print ( 0x12 ) # 十六进制 Hex...
18
123 % 7 = 4
17 % 7 = 3
2 % 7 = 2
234 七进制
4 * 7 ^ 0 + 3 * 7 ^ 1 + 2 * 7 ^ 2 = 4 + 21 + 98 = 123
>>> print(1.34)
1.34
>>> print(0.12e10) #0.12*10^10
1200000000.0
5 / 25 >>> print("1+2+3")
1+2+3
>>> print('1+2+3')
1+2+3
Python 没有字符的数据,一律当成字符串处理,双引号和单引号都可以表示字符串
>>> print(" 张老师说 :" 好好学习 "")
File "<stdin>", line 1
print(" 张老师说 :" 好好学习 "")
^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
>>> print(" 张老师说 :' 好好学习 '")
张老师说 :' 好好学习 '
布尔值常量
只有两个值 True , False , T 和 F 是大写的
>>> print ( True + 1 )
2
>>> print ( False + 1 )
1
True 如果参与运算默认为 1 False 默认为 0 ,这种有意义吗?
复数常量
>>> 1+2j
(1+2j)
>>> complex(1,2)
(1+2j)
>>> (1+2j)*(1-2j)
(5+0j)
标识符
就是我们程序员自定义的一些名称(变量 函数 类)
规则:
由字母、数字、下划线、美元符组成
数字不能开头
是一个连续的词,中间不能有空格分开
规范:
小驼峰:变量 函数 多个单词出现时 第一个单词首字母小写 之后单词首字母都大写 myName
大驼峰:类 所有单词首字母大写 MyName
下划线分割:单词之间用下划线分割 不大写 my_name
起的任何名字必须有含义,就算英文单词记得不多,也可以允许用拼音
关键字
就是一些单词,被 Python 赋予了特殊的含义,不能随便使用
6 / 25 >>> 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']
内置函数名 / 类名
内置函数就是 Python 自带的一些具有特殊功能的函数
>>> print(123)
123
>>> print = 3
>>> print + 4
7
>>> print(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> print(3)
3
>>> show = print # 把 print 指向的那个函数给了 show
>>> print = 3 # 把 3 对象的地址给了 print
>>> print + 4
7
>>> show(7)
7
所以,我们在使用内置函数的时候,一定要注意名称不能够被更改
>>> max ( 432 , 5443 , 1 , 2 , 5 , 6 , 78 , 4 , 5 , 435 )
5443
>>> max = 10
>>> max ( 1 , 2 , 3 )
Traceback ( most recent call last ):
File "<stdin>" , line 1 , in < module >
TypeError : 'int' object is not callable
注释
单行注释
# 后面就是注释的内容 直到换行为止
多行注释
"""
中间多行注释
"""
变量
在 Python 当中 变量其实就是一个万能箱子 他可以存储任何数据
本质:变量它只存储数据在内存中的地址(引用类型变量)
数据类型 变量名 = 数据 # C Java
1.7 数据转换
数据类型转换
int() 将其他有效的数据转为整数
取整
从字符串中解析整数
变量 = 数据
单独定义一个变量时
>>> a = 1
>>> b = 2
同时定义多个变量,给定多个数据
>>> a, b, c = 1, 2, 3
>>> a
1
>>> b
2
>>> c
3
多个变量的值是一样的
>>> a = b = c = 1
>>> a
1
>>> b
1
>>> c
1
int a = (int) 3.14;
>>> int(3.14) # 将小数进行取整操作
3
>>> int("123") # 将数字字符串进行解析(默认十进制),解析出一个整数
123
>>> int("123abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123abc'
>>> int("AD", 16) # 将数字字符串进行十六进制解析,结果都是十进制
173
# 10*16^1 + 13*16^0 = 173
>>> int("91A", 12)
1318
>>> 10 * 12 ** 0 + 1 * 12 ** 1 + 9 * 12 ** 2
1318
>>> int("A1F", 13)
Traceback (most recent call last):
8 / 25 File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 13: 'A1F'
>>> int("91a", 100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: int() base must be >= 2 and <= 36, or 0
base 进制基数 = [2, 36]
>>> int("98*!",12) # 出现特殊符号
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 12: '98*!'
>>> int("10010101") # 注意坑 二进制串特不一定是二进制数字
10010101
>>> int("10010101", 2)
149
float() :将其他的数据转为小数
>>> float(3)
3.0
>>> float(3.14)
3.14
>>> float("3.14")
3.14
>>> float("3.14", 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float expected at most 1 argument, got 2
str() :将其他数据转字符串
>>> str(123)
'123'
>>> str(3.14)
'3.14'
>>> str(print)
'<built-in function print>'
bool() :将其他数据转布尔类型
# 对于数值类型的话 非 0 全是 True 0 就是 False
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(0)
False
>>> bool(3.14)
True
>>> bool(-3.14)
True
9 / 25 >>> bool(0.0)
False
# 对字符串 空串为 False 非空为 True
>>> bool("abc")
True
>>> bool("") # 空串
False
进制转换
>>> bin(123) # 转二进制字符串
'0b1111011'
>>> oct(123) # 转八进制字符串
'0o173'
>>> hex(123) # 转十六进制字符串
'0x7b'
>>> bin("123") # 参数必须是整数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> bin(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
字符与 ASCII 码转换
a~z A~Z 0~9 他们在 ASCII 中的编号都是连续的
ord() :获取字符对应的 ASCII 码编号
>>> ord('a')
97
>>> ord('A')
65
>>> ord('0')
48
chr() :根据给定的 ASCII 码编号获取对应的字符
>>> chr(98)
'b'
>>> chr(57)
'9'
A = 10 B = 11 ...... F = 15
13 - D
chr(ord('A') + 13 - 10)
常见的数学计算
1.8 输入与输出
input()
print()
>>> abs(3.14) # 取绝对值
3.14
>>> abs(-3.14)
3.14
>>> pow(2, 4) # 求 a 的 b 次幂
16
>>> pow(2.0, 4)
16.0
>>> pow(16, 0.5)
4.0
>>> max(1, 2, 3, 4) # 求最值问题
4
>>> min(1,2,3,4)
1
>>> round(3.14) # 四舍五入
3
>>> round(3.51)
4
#num = int(input(" 请输入一个数字 :"))
num = eval ( input ( " 请输入一个数字 :" ))
# input() 默认输入的是一个字符串 ( 整行 )
print ( num + 1 )
"""
TypeError: can only concatenate str (not "int") to str
反向证明输入的是字符串
ValueError: invalid literal for int() with base 10: '123 456'
"""
# 处理一行内多个数据的输入
# eval 处理的数据必须要有逗号分隔
# eval 自动处理字符串解析
# eval 既可以处理单值 也可以处理多值
"""
请输入两个数字 :123,456
579
"""
num1 , num2 = eval ( input ( " 请输入两个数字 :" ))
print ( num1 + num2 )
print ( "Hello World" )
print ( 1 + 2 + 3 )
print ( 1 , 2 , 3 , "Hello World!" ) # 多数据输出 用空格分隔
print ( 1 , 2 , 3 , sep = "#" ) # sep 默认空格
1.9 运算符
算数运算符
加法:数值相加,序列拼接
减法:数值相减
乘法:数值相乘,序列增倍
除法:小数除 / ,整数除 //
整数除 只要两边都是整数 结果一律为整数 但凡有一个小数 结果就是小数(只有整数位,小数位都为 0 )
幂运算
print ( 1 , 2 , 3 , end = "!!!" ) # end 输出的解围 默认 "\n"
# print(*args, sep=' ', end='\n', file=None, flush=False)
print ( 1 , 2 , 3 , end = "!!!" )
print ( "Hello World" , end = "!!!" )
print ( "Hello World" , end = "!!!" )
print () # 单独一个 print 换行的意思 其实打印的是空串
# 格式化输出
name = " 旺财 "
age = 18
height = 1.23
print ( " 它叫 " , name , " ,今年 " , age , " 岁 " , sep = "" )
# %s 对应字符串 %d 对应整数 %f 对应小数
print ( " 它叫 %s ,今年 %d 岁,身高 %.2f 米 " % ( name , age , height ))
>>> 1 + 2
3
>>> "123" + "456"
'123456'
>>> 3 * 6
18
>>> " 我爱你 " * 3
' 我爱你我爱你我爱你 '
>>> 10 / 2
5.0
>>> 10 // 2
5
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
>>> 10.0 // 3
3.0
>>> 10.5 // 3
3.0
12 / 25 >>> 2 ** 3
8
>>> 16 ** 0.5
4.0
取余: 10 / 3 = 3 ~ 1
>>> 10 % 3
1
取余经常用于哪些场景,带有数据重复或循环的情况
22 日对应周五, 22 % 7 = 1 余数为 1 则对应周五 0 对应周四 ....
30 % 7 = 2 对应周六
布尔判断运算符
运算结果一律为布尔值
大于 小于 大于等于 小于等于 不等于 等于
> < >= <= != ==
Python 允许连续比较
>>> 1 < 2 < 3
True
>>> 1 < 2 and 2 < 3
True
在 Python 当中 == 到底比得是啥?
答:比的是具体对象的值
>>> a = 1
>>> b = 1
>>> id(a) # id 取变量中存储的数据对象在内存中的地址
140715464473016
>>> id(b)
140715464473016
>>> a = 1000
>>> b = 1000
>>> id(a)
3267440575376
>>> id(b)
3267440589968
可以发现 a 和 b 在为 1000 时 对象地址不一样?
因为在 Python 当中 只有 -5~256 Python 会自动创建这些数据对象,提供给调用者使用
也就意味着如果创建该范围之外的数据对象的话, Python 则重新创建新的对象出来
a = 1000, b = 1000 其实是两个 1000 数据的对象
a == b 比的是对象的内容 但是 a 和 b 存的地址不一样
a = 1, b = 1, 其实只有一个 1 数据的对象
13 / 25 a == b 比的是对象的内容 但是 a 和 b 存的地址一样
增强型赋值运算符
+= -= *= /= //= **= %=
a += 2
a = a + 2
b **= 2
b = b ** 2
额外多说一句:在 Python 中 是不存在 ++ -- 这种自增运算符的!
int i = 1 ;
i ++ ;
System . out . println ( i );
System . out . println ( i ++ );
int j = i ++ ;
System . out . println ( i );
System . out . println ( j );
i = i ++ ;
System . out . println ( i );
i = i ++ ;
System . out . println ( i );
i++ 流程
1. 开辟临时存储区
2. 将 i 的值复制到临时存储区内
3. i 自身 +1
4. 临时存储区的值等待被调用(输出 赋值 参与运算)
System . out . println ( x ++ + ++ x + ++ x + x ++ ); // 12
System . out . println ( x ); // 5
逻辑运算符
与 或 非 = and or not ( && || ! )
与:全真则真 有假则假
或:有真则真 全假则假
非:取反
>>> 1 < 2 and 2 < 3
True
>>> 1 < 2 or 2 > 3
True
>>> not 1 < 2
False
& 与 && 的区别
int x = 0;
int y = 0;
System.out.println(x++ < 0 & y ++ < 0); // 无论左边是否为假 右边都要计算
System.out.println(x); //1
System.out.println(y); //1
int x = 0;
int y = 0;
System.out.println(x++ < 0 && y ++ < 0); // 如果左边是假 右边不计算
System.out.println(x); //1
System.out.println(y); //0
&& 就是为了避免一些没有必要的计算 提高效率
位运算符
& 按位与
>>> 13 & 7
5
1101
0111
0101 = 5
| 按位或
>>> 13 | 7
15
1101
0111
1111 = 15
>> 右移
>>> 16 >> 2
10000
100|00
100 = 4
16 / 2 ^ 2
<< 左移
>>> 2 << 3
16
0010
0010000
10000 = 16
2 * 2 ^ 3
~ 取反 符号取反再减 1
>>> ~15
-16
01111 = 15
10000 = -16
^ 异或:相等为假 不同为真
>>> 13 ^ 7
10
1101
0111
1010 = 10
关于变量交换值
a = 1
b = 3
temp = a
a = b
b = temp
a, b = b, a # Python 自带的交换特点
只针对整数
a = 10
b = 100
a = a + b # 110
b = a - b # 10
a = a - b # 100
只针对整数
a = a ^ b
b = a ^ b
a = a ^ b
成员运算符
in 和 not in
判断一个元素是否在另一个序列中
>>> "abc" in "sakjdgjhsgadugashjdvasvdjgsa"
False
>>> "abc" in "sakjdgabca"
True
>>> 1 in [2,3,4]
False
从属 / 身份运算符
is 和 not is
判断两个变量指向的对象是否是同一个对象(比地址)
>>> a = 1
>>> b = 1
>>> a == b
True
>>> a is b
True
>>> a == 1000
False
>>> a = 1000
>>> b = 1000
>>> a == b
True
>>> a is b
False
>>> a = "abc" # 字符串
>>> b = "abc" # 之前已经创建了 "abc" 这里直接复用 而不是重新创建 跟整数是有区别的
>>> a == b
True
>>> a is b
True
>>> id(a)
140715463387184
>>> id(b)
140715463387184

1.12 数组列表
序列:存储一堆数据的集合 / 容器
列表、字符串、元组、集合、字典
序列通用操作
索引 / 角标
切片 就是获取序列中某一个连续子区间
print ( s )
n = eval ( input ())
if n == 1 or n == 2 :
print ( n )
else : # n = 5
a = 1
b = 2
c = 0
for i in range ( 3 , n + 1 ):
c = a + b
a = b
b = c
print ( c )
a , n = eval ( input ())
sum = 0
num = 0
for i in range ( n ):
num = num * 10 + a # 2 22 222
sum += num
print ( sum )
>>> arr = [1,2,3,4,5,6,7,8,9]
>>> arr[0]
1
>>> arr[8]
9
>>> arr[-1] # 倒数第 1
9
>>> arr[-2] # 倒数第 2
8
>>> arr[-100]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> arr[100]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
序列名 [a : b : c] range(a, b, c) 基本类似
>>> arr[2:] # 从角标 2 开始向尾遍历 步长为 1
[3, 4, 5, 6, 7, 8, 9]
>>> arr[2::2] # 从角标 2 开始向尾遍历 步长为 2
[3, 5, 7, 9]
>>> arr[:6] # 从头开始到角标 6( 不取 ) 步长为 1
[1, 2, 3, 4, 5, 6]
>>> arr[:6:3] # 从头开始到角标 6( 不取 ) 步长为 3
[1, 4]
>>> arr[:] # 从头到尾
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[::]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[::2]
[1, 3, 5, 7, 9]
======================================= 特殊的
>>> arr[-1:-7] # 从尾到头 步长必须负数
[]
>>> arr[-1:-7:-1]
[9, 8, 7, 6, 5, 4]
>>> arr[-9:7] # 从头到尾 步长为正数
[1, 2, 3, 4, 5, 6, 7]
>>> arr[0:7]
[1, 2, 3, 4, 5, 6, 7]
>>> arr[-9:-2] # 从头到尾 步长为正数
[1, 2, 3, 4, 5, 6, 7]
连接和重复 + *
成员资格
>>> 1 in arr
True
>>> 10 in arr
False
长度与最值
>>> len(arr) # 获取序列的长度
9
>>> len(arr)
9
>>> max(arr)
9
>>> min(arr)
1
>>> s = "ABC"
>>> len(s)
3
>>> max(s)
'C'
>>> min(s)
'A'
常见操作
创建问题
"""
列表
1. 存储多个数据 数据不一定都是同一个类型 但是为了方便操作 建议存一样的类型
2. 可以通过索引 / 角标来访问元素
3. 可变长的数组 我们后续可以在列表中进行 增 删
4. 用一对中括号 []
"""
# 创建一个空的列表
arr = []
print ( arr )
# 创建一个具有若干元素的列表
arr = [ 1 , 2 , 3 , 4 ]
print ( arr )
# 创建一个具有长度但是没有值的列表
arr = [ None ] * 5
print ( arr )
# 通过【列表推导式 / 解析式】来进行创建
# [ 目标值表达式 for 目标值 in 迭代对象 if ....]
# 创建 1~100 当中 能够被 3 整除 且 能够被 5 整除 的所有数字
"""
for x in range(1, 101):
if x % 3 == 0 and x % 5 == 0:
print(x)
"""
arr = [ x for x in range ( 1 , 101 ) if x % 3 == 0 and x % 5 == 0 ]
print ( arr )
# 创建 1~100 当中 偶数
arr = [ x for x in range ( 1 , 101 ) if x % 2 == 0 ]
print ( arr )
# 水仙花数
for num in range ( 100 , 1000 ):
a = num % 10
b = num // 10 % 10
c = num // 100
if a ** 3 + b ** 3 + c ** 3 == num :
print ( num )
arr = [ num for num in range ( 100 , 1000 ) if ( num % 10 ) ** 3 + ( num // 10 % 10 ) **
3 + ( num // 100 ) ** 3 == num ]
print ( arr )
arr = [ x * 3 + " 哈哈 " for x in "ABCDEFG" ]
print ( arr )
# 通过输入来获取元素
"""
5
"1" "2" "3" "4" "5"
"""
n = eval ( input ())
arr = input (). split ( " " ) # 将输入的数据以空格分割 分割的结果就是列表
print ( arr )
arr = [ int ( x ) for x in arr ]
print ( arr )
遍历问题
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
# 通过角标遍历
for i in range ( len ( arr )):
print ( arr [ i ])
# 通过 foreach 遍历
for num in arr :
print ( num )
最值问题
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
# 最大值
maxNum = arr [ 0 ]
minNum = arr [ 0 ]
for i in range ( 1 , len ( arr )):
if arr [ i ] > maxNum :
maxNum = arr [ i ]
if arr [ i ] < minNum :
minNum = arr [ i ]
print ( maxNum )
print ( minNum )
存在性问题
arr = [ 1 , 2 , 3 , 4 , 5 , 4 , 6 , 4 , 7 , 8 , 9 ]
# 元素是否存在
key = 10
for num in arr :
if num == key :
print ( " 存在 " )
break
else :
print ( " 不存在 " )
# 元素在哪个位置 从左到右第 1 次出现的角标 不存在返回 -1
key = - 4
index = 0
for i in range ( len ( arr )):
if arr [ i ] == key :
index = i
break
else :
index = - 1
print ( index )
翻转问题
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
# 0 1 2 3 4 5 6 7 8
arr = arr [ - 1 :: - 1 ]
print ( arr )
for i in range ( 0 , len ( arr ) // 2 ):
j = len ( arr ) - 1 - i
arr [ i ], arr [ j ] = arr [ j ], arr [ i ]
print ( arr )
left = 0
right = len ( arr ) - 1
while left < = right :
arr [ left ], arr [ right ] = arr [ right ], arr [ left ]
left += 1
right -= 1
print ( arr )
排序算法
选择排序
冒泡排序
插入排序
查找算法
二分查找:要求数据必须有序
arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
minIndex = 0
maxIndex = len ( arr ) - 1
midIndex = ( minIndex + maxIndex ) // 2
key = 8
while arr [ midIndex ] ! = key :
if arr [ midIndex ] < key :
minIndex = midIndex + 1
else :
maxIndex = midIndex - 1
if minIndex > maxIndex :
midIndex = - 1
break
midIndex = ( minIndex + maxIndex ) // 2
print ( midIndex )
  • 18
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值