python基础-数据类型

第 1 章 变量进阶------变量类型

Python 中数据类型可以分为数字型和⾮数字型 。

  • 数字型

    • 整型 ( int )
    • 浮点型( float )
    • 布尔型( bool )
      • 真 True ⾮ 0 数 —— ⾮零即真
      • 假 False 0
  • 非数字型

    • 列表(List)
    • 元组
    • 字典
    • 集合
    • 字符串

    在 Python 中,所有非数字型变量都⽀持以下特点:

    1. 都是一个序列 ;

    2. 通过 变量名[索引] 方式取值 ;

    3. 通过 for in 遍历;

    4. 可以计算⻓度、最⼤和最⼩值 。

第 2 章 变量进阶------列表

List (列表) 是 Python 中使⽤最频繁的数据类型,在其他语⾔中通常叫做数组 ,专⻔⽤于存储 一串信息 。

  • 列表⽤ [] 定义,列表中的数据之间使⽤ , 分隔
  • 列表的索引从 0 开始
  • 索引就是数据在列表中的位置编号,索引⼜可以被称为下标

注意:从列表中取值时,如果超出索引范围程序会报错。

# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
# 显示列表第一个元素的值
print(list1[0])
print(list1[1])
print(list1[2])

# IndexError: list index out of range
# 错误,列表没有[3]这个值
print(list1[3])

一、查看列表所有方法

  • 通过 dir() 函数查看某类型中定义的⽅法
# 定义一个列表变量,名字叫 list1,有三个元素 
list1 = ["刘备","关羽","张飞"] 
# 通过 dir 函数显示列表所有的方法 
print(dir(list1))

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

二、列表常⽤方法

分类 方法 说明
增加 insert(索引,数据) 在指定位置插入数据
append(数据) 在末尾追加数据
extend(列表) 追加另一个列表的值
修改 列表[索引] = 值 修改指定索引的数据
删除 del(列表[索引]) 删除指定索引的数据
remove(数据) 删除第一次出现的指定数据
pop() 删除末尾数据
pop(索引) 删除指定索引数据
clear() 清空列表
统计 count(数据) 返回指定数据在列表中出现的次数
index(数据) 返回数据在列表中的索引值,如果找不到抛出异常
排序 sort() 升序排序
sort(reverse=True) 降序排序
reverse() 逆置,反转
去重 set()

增加:

1、insert

  • insert作用是在列表指定位置插入指定的值
  • 语法
insert(位置索引,要插入的值)  ------list1.insert(1,'吕布')
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#插入
list1.insert(1,'吕布')
print(list1)

['刘备', '关羽', '张飞']
['刘备', '吕布', '关羽', '张飞']

Process finished with exit code 0

2、append

  • append作用是列表最后位置添加成员
  • 语法
append(要添加的值) -----list1.append('吕布')
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#添加
list1.append('吕布')
print(list1)

['刘备', '关羽', '张飞']
['刘备', '关羽', '张飞', '吕布']

Process finished with exit code 0

3、extend

  • extend作用是把一个列表的成员追加到指定列表的后面
  • 语法
extend(列表的变量名)   -----list1.extend(list2)
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#定义另一个列表 list2
list2=['孙权','周瑜']

list1.extend(list2)
print(list1)

['刘备', '关羽', '张飞']
['刘备', '关羽', '张飞', '孙权', '周瑜']

Process finished with exit code 0

修改:

4、 列表[索引] = 值

示例:修改list1 = ["刘备","关羽","张飞"] 刘备改为吕布

# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
list1[0]='吕布'
print(list1)

['刘备', '关羽', '张飞']
['吕布', '关羽', '张飞']

Process finished with exit code 0

删除:

5、del

  • del作用是删除指定索引的数据

  • 语法

del(列表变量名[索引])   -----del(list1[0])

示例:删除list1 = ["刘备","关羽","张飞"] 中的刘备

# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#s删除
del(list1[0])
print(list1)

['刘备', '关羽', '张飞']
['关羽', '张飞']

Process finished with exit code 0

6、remove

  • remove作用是根据指定的值删除数据
  • 语法
remove(要删除的值)    ----list1.remove('刘备')

示例:删除list1 = ["刘备","关羽","张飞"] 中的刘备

# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#删除
list1.remove('刘备')
print(list1)

['刘备', '关羽', '张飞']
['关羽', '张飞']

Process finished with exit code 0

7、pop

  • pop删除末尾的数据
  • 语法
pop()  ------list1.pop()
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#删除
list1.pop()
print(list1)

['刘备', '关羽', '张飞']
['刘备', '关羽']

Process finished with exit code 0

8、pop(索引)

  • pop(索引)作用 删除指定索引数据 功能与del类似
  • 语法
pop(索引)  ----list1.pop(0)
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#删除
list1.pop(0)
print(list1)

['刘备', '关羽', '张飞']
['关羽', '张飞']

Process finished with exit code 0

9、clear

  • 清空列表
  • 语法
clear()  -----list1.clear()
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
print(list1)
#删除
list1.clear()
print(list1)

['刘备', '关羽', '张飞']
[]

Process finished with exit code 0

统计(查找)

11、count

  • count 代表指定数据在列表中出现的次数(如果有多个值,返回数量,如果没有值,返回0)
  • 语法
count(数据)  ----list1.count('张飞')
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞","张飞"]
print(list1)
#统计
print(list1.count('张飞'))

['刘备', '关羽', '张飞', '张飞']
2

Process finished with exit code 0

12、index

  • index 返回数据在列表中的索引值,如果找不到抛出异常(如果有多个值,返回第一个,可以接指定的索引开始找)
  • 语法
index(数据)  ----list1.index("张飞")
			----list1.index("张飞",3)
# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞","吕布","张飞"]
print(list1)
#统计
print(list1.index("张飞"))
print(list1.index("张飞",3))

['刘备', '关羽', '张飞', '吕布', '张飞']
2
4

Process finished with exit code 0

排序:

13、sort

  • sort() 对列表成员从小到大排序
  • 语法
sort()  -----list1.sort()
list1=[4,2,3,45,12,67]
print(list1)
list1.sort()
print(list1)

[4, 2, 3, 45, 12, 67]
[2, 3, 4, 12, 45, 67]

Process finished with exit code 0

14、sort(reverse=True)

  • sort(reverse=True) 对列表成员从大到小排序
  • 语法
sort(reverse=True)   --list1.sort(reverse=True)
list1=[4,2,3,45,12,67]
print(list1)
list1.sort()
print(list1)

list1.sort(reverse=True)
print(list1)

[4, 2, 3, 45, 12, 67]
[2, 3, 4, 12, 45, 67]
[67, 45, 12, 4, 3, 2]

Process finished with exit code 0

15、reverse

  • reverse 逆置,反转--把列表所有成员顺序颠倒
  • 语法
reverse()  ----list1.reverse()
list1=[4,2,3,45,12,67]
print(list1)
list1.reverse()
print(list1)

去重:

16、set

  • set() 去重列表中的重复项
  • 语法
set()   ----list(set(l))
  • 示例:现在有一个列表 L=[1,2,3,4,5,6,6,5,4,3,2,1],去重列表中的重复项

第一种方法:set()去重

l=[1,2,3,4,5,6,6,5,4,3,2,1]
list1=list(set(l))
print(list1)

[1, 2, 3, 4, 5, 6]

Process finished with exit code 0

第二种方法:遍历

l=[1,2,3,4,5,6,6,5,4,3,2,1]

new_list=[]
for i in l:
    if i not in new_list:
        new_list.append(i)

print(new_list)

[1, 2, 3, 4, 5, 6]

Process finished with exit code 0

三、循环遍历列表

  • 遍历就是从头到尾依次从列表中获取数据

1、for遍历列表

  • 语法
for 变量名 in 列表:
	代码
	
列表中有多少成员,for就会循环多少次
变量名代表for每次循环的时候,得到的列表成员的值

在 Python 中,可以使⽤ for 循环遍历所有⾮数字型类型的变量,包括:列表、元组、字典以及字符串 。

# 定义一个列表变量,名字叫 list1,有三个元素
list1 = ["刘备","关羽","张飞"]
# 通过 for 循环遍历 list1 中所有的元素
for n in list1:
    print(n)
       
    
刘备
关羽
张飞

Process finished with exit code 0
  • 课堂练习---list1=["张飞", "刘备", "关羽", "刘邦", "刘老二" ,"曹操" ],写代码判断列表中名字为3个字的人有几个?
#判断字符串有几个字符?
n="刘老二"
sum=0
for a in n:
    sum=sum+1
    
print(sum)

3

Process finished with exit code 0
list1=["张飞", "刘备", "关羽", "刘邦", "刘老二" ,"隔壁老王" ]
#写代码判断列表中名字为3个字的人有几个

#思路:首先要把每个名字遍历一遍  #只要知道sum出现3的次数,就是字符答案
num1=0   #存放名字为3个字出现的次数
for n in list1:   #n是列表中每个成员
    sum=0
    for a in n:  #a是字符串n中每个字符个数
        sum=sum+1
    if sum == 3:
        num1=num1+1

print(num1)

2

Process finished with exit code 0

或者

num1=0   #存放名字为3个字出现的次数
for n in list1:   #n是列表中每个成员
    if len(n) == 2:
        num1=num1+1

print(num1)

四、拆包

  • 拆包就是把一个列表中每个值拆出来
  • 拆包操作同样适用于元组,集合和字典
  • 语法
变量名1,变量名2,变量名n = 列表变量
等号左边的变量数量要和等号右边的列表中成员数量一致
# 定义一个列表
list1 = ["张三", 30, 4.5]
# 通过对列表进行拆包方式获取列表中每个元素的值
a, b, c = list1
print(a, b, c)

张三 30 4.5

Process finished with exit code 0

a=list1[0]
b=list1[1]
c=list1[2]

五、列表推导式

  • 所谓的列表推导式,就是指轻量级的循环创建列表的⽅法---(快速生成一个列表)
  • 语法
列表变量名=[x for x in range(开始值,结束值,步长)]

1、基本的⽅式

list1=[x for x in range(1,10)]
print(list1)

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

Process finished with exit code 0

2.、在推导过程中使⽤if

list1=[x for x in range(1,10)]
print(list1)
list2=[x for x in range(1,10) if x % 2 == 0]
print(list2)

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

Process finished with exit code 0
  • 课堂练习----用列表推导式,创建一个列表,内容为[0, 10, 20, 30, 40, 50, 60,70, 80, 90, 100]
list1=[x for x in range(0,101,10)]
print(list1)

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Process finished with exit code 0
list1=[x for x in range(0,101) if x % 10 ==0]
print(list1)

3、列表中的数据类型不统一

  • 当列表中成员数据类型不统一,但是又要在for中通过一条代码来处理不同类型的数据,需要把数据做一个类型转换
list1 = ["刘备","关羽","张飞"]
a=1
for n in list1:
    print("列表第%d个成员的值是%s"%(a,n))
    a=a+1
    
    
列表第1个成员的值是刘备
列表第2个成员的值是关羽
列表第3个成员的值是张飞

Process finished with exit code 0
list1 = ["刘备","关羽","张飞",3,4.5]
a=1
for n in list1:
    print("列表第%d个成员的值是%s"%(a,str(n)))
    a=a+1
    
列表第1个成员的值是刘备
列表第2个成员的值是关羽
列表第3个成员的值是张飞
列表第4个成员的值是3
列表第5个成员的值是4.5

Process finished with exit code 0
sum=0
list1=[56,'32',45,'6']
for n in list1:
    sum=sum+int(n)

print(sum)

139

Process finished with exit code 0

第 3 章 变量进阶------公共方法

公共方法同样适用于元组,集合,字典,字符串等类型

分类 方法 说明
统计 len(列表) 返回列表元素个数
max(列表) 返回列表中最大的数据
min(列表) 返回列表中最小的数据
成员运算符 值 in 列表 判断值是否在列表中,存在返回 True,不存在返回 False
值 not in 列表 判断值是否在列表中,存在返回 False,不存在返回 True

len

list1=[4,2,5,3]
print(len(list1))

list2="hello"
print(len(list2))

4
5

Process finished with exit code 0

max

min

list1=[4,2,5,30]
print(max(list1))
print(min(list1))

30
2
Process finished with exit code 0

in

  • 判断指定的值是否在列表中存在

课堂练习:

  • 定义一个列表变量,内容如下list1=["张飞", "刘备", "关羽", "刘邦", "刘老二" ,"隔壁老王" ]

    查找列表中是否有刘备,如果有将其删除

list1=["张飞", "刘备", "关羽", "刘邦", "刘老二" ,"隔壁老王" ]
print(list1)
if "刘备" in list1:
    list1.remove("刘备")
print(list1)

['张飞', '刘备', '关羽', '刘邦', '刘老二', '隔壁老王']
['张飞', '关羽', '刘邦', '刘老二', '隔壁老王']

Process finished with exit code 0

课堂练习:

求列表的平均值

list2=[3,5,67,2,34,12,5,11]
sum=0
for i in list2:
    sum=sum+i
print(sum/len(list2))

17.375

Process finished with exit code 0

not in

  • 判断指定的值是否不在列表中

课堂练习:

示例:现在有一个列表 L=[1,2,3,4,5,6,6,5,4,3,2,1],去重列表中的重复项

l=[1,2,3,4,5,6,6,5,4,3,2,1]

new_list=[]
for i in l:
    if i not in new_list:
        new_list.append(i)

print(new_list)

[1, 2, 3, 4, 5, 6]

Process finished with exit code 0

第 4 章 变量进阶------元组

  • Tuple (元组)与列表类似,不同之处在于元组的元素不能修改
  • 元组⽤ () 定义
# 定义一个元组,名字叫 tuple1,有三个元素
tuple1 = ("孙权", 28, 1.75)
print(tuple1)

('孙权', 28, 1.75)

Process finished with exit code 0
  • 元组只有一个元素时,元素后面需要添加逗号
# 元组中只包含一个元素时,需要在元素后⾯添加逗号 
tuple3 = (50, )
  • 定义元组时, ()可以省略
tuple4 = "张飞", 30 
pytuple5 = "吕布",
  • 元组只有一个元素,尝试后面加和不加逗号的差别
    • 加逗号类型是元祖,不加逗号类型是字符串
tuple1 = ("hello")
print(tuple1)
print(type(tuple1))

tuple2 = ("hello",)
print(tuple2)
print(type(tuple2))

hello
<class 'str'>
('hello',)
<class 'tuple'>

Process finished with exit code 0

一、元组常⽤方法

元组的常用方法与列表类似, 元组的内容不可修改,所以没有增加、修改和删除相关方法。

示例:

  • 根据下标取值
tuple1=('刘备','关羽','张飞')
a=tuple1[1]
print(a)

关羽

Process finished with exit code 0
  • count() --统计
tuple1=('刘备','关羽','张飞')
a=tuple1.count('刘备')
print(a)

1

Process finished with exit code 0
  • index() --返回数据在元祖中的索引值
tuple1=('刘备','关羽','张飞')
a=tuple1.index('张飞')
print(a)

2

Process finished with exit code 0
  • len() ---返回长度/数量
tuple1=('刘备','关羽','张飞')
a=len(tuple1)
print(a)

3

Process finished with exit code 0
  • max
  • min
  • in
  • not in

二、循环遍历元组

与遍历列表类似

tuple1=('刘备','关羽','张飞',4,12)
for i in tuple1:
    print(i)
    
刘备
关羽
张飞
4
12

Process finished with exit code 0

三、元组和列表之间的转换

  • 把列表转化为元组目的是让列表不可以被修改,以保护数据安全
  • 使⽤ list 函数可以把元组转换成列表
  • 使⽤ tuple 函数可以把列表转换成元组

1、列表转换为元组

  • tuple(列表)
list1 = ["张三", 30, 4.5]
tuple1=tuple(list1)
print(tuple1)
print(type(tuple1))

('张三', 30, 4.5)
<class 'tuple'>

Process finished with exit code 0

2、元组转换为列表

  • list(元组)
tuple1=('刘备','关羽','张飞',4,12)
list1=list(tuple1)
print(list1)
print(type(list1))

['刘备', '关羽', '张飞', 4, 12]
<class 'list'>

Process finished with exit code 0

课堂练习:把元组追加放到列表后面

list1 = ["刘备","关羽","张飞"]

tuple1 = ("曹操", "周瑜")

  • 将元组 tuple1 的元素追加到 list1 元素后面
    • (不用将tuple1转换为列表,可以直接添加,因为tuple1的值没有发生变化)
list1 = ["刘备","关羽","张飞"]
tuple1 = ("曹操", "周瑜")

list1.extend(tuple1)
print(list1)

['刘备', '关羽', '张飞', '曹操', '周瑜']

Process finished with exit code 0

课堂练习:把元组放在列表前面

list1 = ["刘备","关羽","张飞"]

tuple1 = ("曹操", "周瑜")

  • 将元组 tuple1 的元素放到 list1 元素前面
list1 = ["刘备","关羽","张飞"]
tuple1 = ("曹操", "周瑜")
n=0
for i in tuple1:
    list1.insert(n,i)
    n=n+1

print(list1)

['曹操', '周瑜', '刘备', '关羽', '张飞']

Process finished with exit code 0

第 5 章 变量进阶------集合

  • 集合用{}定义
    • 创建空集合 变量名 = set()
    • -----不能通过 变量名 = {}来创建空集合;
# 定义一个空集合 set1
set1 = set()
  • 集合和列表的区别:
    • 列表是有序的对象集合
    • 集合是⽆序的对象集合
    • 同一个集合内值不允许重复
# 定义一个集合 set1
set1 = {"张飞", 33, 1.75}
print(set1)

{'张飞', 33, 1.75}

Process finished with exit code 0

一、集合常⽤操作

分类 方法 说明
增加 add(值) 增加值
删除 pop() 删除随机一个值
remove(值) 删除指定值
clear() 清空集合

增加:

add

  • 语法
set1.add('刘备')
# 定义一个集合 set1
set1 = {"张飞", 33, 1.75}
print(set1)

set1.add('刘备')
print(set1)

{33, '张飞', 1.75}
{33, '刘备', '张飞', 1.75}

Process finished with exit code 0

删除:

pop

  • 删除随机一个值
  • 语法
set1.pop()
# 定义一个集合 set1
set1 = {"张飞", 33, 1.75}
print(set1)

set1.pop()
print(set1)

{33, '张飞', 1.75}
{'张飞', 1.75}

Process finished with exit code 0

remove

  • 删除指定的值
  • 语法
set1.remove(33)
# 定义一个集合 set1
set1 = {"张飞", 33, 1.75}
print(set1)

set1.remove(33)
print(set1)

{33, '张飞', 1.75}
{'张飞', 1.75}

Process finished with exit code 0

clear

  • 删除所有的值
  • 语法
set1.clear()
# 定义一个集合 set1
set1 = {"张飞", 33, 1.75}
print(set1)

set1.clear()
print(set1)

{33, '张飞', 1.75}
set()

Process finished with exit code 0

课堂练习:

# 定义一个空集合变量,通过 input 函数,向集合里输入任意 5 个整数

# 显示集合中的最小值

set1=set()
a=0
while a<5:
    set1.add(int(input("请输入一个整数")))
    a=a+1

print(set1)
print(min(set1))

请输入一个整数1
请输入一个整数34
请输入一个整数4
请输入一个整数5
请输入一个整数6
{1, 34, 4, 5, 6}
1

Process finished with exit code 0

二、循环遍历集合

遍历就是依次从集合中获取所有值

# 定义一个集合 set1
set1 = {"张飞", 33, 1.75}

for i in set1:
    print(i)
    
33
张飞
1.75

Process finished with exit code 0

课堂练习:

# 定义一个空集合变量,通过 input 函数,向集合里输入任意 3 个字符串*

# 遍历集合,显示集合中所有的字符串

set1=set()
a=0
while a<3:
    set1.add(int(input("请输入一个整数")))
    a=a+1

for i in set1:
    print(i)
    
请输入一个整数21
请输入一个整数3
请输入一个整数345
345
3
21

Process finished with exit code 0

第 6 章 变量进阶------字典

  • dictionary (字典)通常⽤于存储“键值对” 数据,键与值之间用冒号分隔。
    • 键 key 是索引,同一个字典内,键名不能重复
    • value 是数据
  • 字典用{}定义
    • 通过变量名 = {}创建一个空字典
# 定义一个空字典 
dict1 = {}

字典与集合的区别:

  • 集合中只有值
  • 字典是包含键与值的键值对

一、字典常⽤操作

分类 方法 说明
增加/修改 字典[“键”] = 值 如果键存在,代表修改已有键的值
如果键不存在,代表新增键值对
删除 pop(“键”) 删除指定键
clear() 清空字典
得到值 字典[“键”] 返回指定键的值

增加/修改

  • 语法

    #新增一个键值对,键为class  值为1班
    dict1["class"]="1班"
    
    #修改键name对应的值
    dict1["name"]="关羽"
    
dict1 = {"name":"周瑜","age":32,"sex":"男"}
print(dict1)

#修改键name对应的值
dict1["name"]="关羽"
print(dict1)

#新增一个键值对,键为class  值为1班
dict1["class"]="1班"
print(dict1)

{'name': '周瑜', 'age': 32, 'sex': '男'}
{'name': '关羽', 'age': 32, 'sex': '男'}
{'name': '关羽', 'age': 32, 'sex': '男', 'class': '1班'}

Process finished with exit code 0

删除:

pop

  • 删除一个键,一旦键被删除,对应的值也被删除了
  • 语法
dict1.pop('name')
dict1 = {"name":"周瑜","age":32,"sex":"男"}
print(dict1)
dict1.pop('name')
print(dict1)

{'name': '周瑜', 'age': 32, 'sex': '男'}
{'age': 32, 'sex': '男'}

Process finished with exit code 0

clear

  • 清空字典
  • 语法
dict1.clear()
dict1 = {"name":"周瑜","age":32,"sex":"男"}
print(dict1)
dict1.clear()
print(dict1)

{'name': '周瑜', 'age': 32, 'sex': '男'}
{}

Process finished with exit code 0

得到值

  • 得到字典中键对应的值
  • 语法;
dict1["age"]
dict1 = {"name":"周瑜","age":32,"sex":"男"}
print(dict1)

a=dict1["age"]
print(a)

{'name': '周瑜', 'age': 32, 'sex': '男'}
32

Process finished with exit code 0

课堂练习:

dict1 = {"name":"周瑜","age":32,"id":"001"} 
# 字典中增加一个键值对’sex’:’男’; 
# 删除键’id’; 
# 将键’age’的值修改为 26。
dict1 = {"name":"周瑜","age":32,"id":"001"}
print(dict1)

# 字典中增加一个键值对’sex’:’男’;
dict1["sex"]="男"
print(dict1)

# 删除键’id’;
dict1.pop("id")
print(dict1)

# 将键’age’的值修改为 26。
dict1["age"]="26"
print(dict1)

{'name': '周瑜', 'age': 32, 'id': '001'}
{'name': '周瑜', 'age': 32, 'id': '001', 'sex': '男'}
{'name': '周瑜', 'age': 32, 'sex': '男'}
{'name': '周瑜', 'age': '26', 'sex': '男'}

Process finished with exit code 0

二、循环遍历字典

遍历就是依次从字典中获取所有键值对

dict1 = {"name":"周瑜","age":32,"id":"001"}
for i in dict1:
    #i 代表键   dict1[i]输出键对应的 值
    print(i,dict1[i]) 
    
name 周瑜
age 32
id 001

Process finished with exit code 0

三、循环遍历字典二----拆包方式

  • 字典的 items 方法获取字典中的键值对
  • items 方法返回包含字典键值对的元组
dict1 = {"name":"周瑜","age":32,"id":"001"}
for i in dict1.items():
    print(i)
print(type(i))
    
('name', '周瑜')
('age', 32)
('id', '001')

<class 'tuple'>

Process finished with exit code 0
  • 通过对元组拆包的方式获取键和值
dict1 = {"name":"周瑜","age":32,"id":"001"}
for a,b in dict1.items():
    # a 为键,b 为值
    print(a,b)
    
name 周瑜
age 32
id 001

Process finished with exit code 0

课堂练习:

dict1 = {"a":23,"b":4,"c":9,"d":3,"e":12} 
# 循环遍历字典, 显示字典每个键和键对应的值
# 显示值9对应的键名
# 循环遍历字典, 显示字典每个键和键对应的值
dict1 = {"a":23,"b":4,"c":9,"d":3,"e":12}
#第一中方法
for i in dict1:
    print(i,dict1[i])

#第二种方法
for a,b in dict1.items():
    print(a,b)
dict1 = {"a":23,"b":4,"c":9,"d":3,"e":12}

#显示值9对应的键名
#思路:遍历字典,在遍历的时候,检查值是否为9,如果为9 显示9对应的键
for i in dict1:
    if dict1[i]==9:
        print(i)

c

Process finished with exit code 0

第 7 章 变量进阶------字符串

  • 字符串就是⼀串字符,是编程语⾔中表示⽂本的数据类型。
  • 在 Python 中可以使⽤⼀对双引号 " 或者⼀对单引号 ' 定义⼀个字符串
虽然可以使⽤ \" 或者 \' 做字符串的转义,但是在实际开发中: 如果字符 串内部需要使⽤ " ,可以使⽤ ' 定义字符串。
  • 可以使⽤ [索引] 获取⼀个字符串中指定位置的字符,索引计数从 0 开始

    # 定义一个字符串 str1
    str1 = "我爱 python"
    print(str1[1])
    
    爱
    
    Process finished with exit code 0
    

一、遍历字符串中每个字符

# 定义一个字符串 str1
str1 = "我爱 python"
for i in str1:
    print(i)
    
我
爱
 
p
y
t
h
o
n

Process finished with exit code 0

二、字符串的常⽤方法

分类 方法 说明
字符串[索引] 得到指定索引位置的字符
isalpha() 判断字符串是否为纯字母构成
isdigit() 判断字符串是否为纯数字构成
islower() 判断字符串中所有字母是否都为小写
isupper() 判断字符串中所有字母是否都为大写
查找和替换 find(“子串”) 查找子串在字符串中出现的位置,找不到返回 -1
replace(“子串”, ”新子串”) 查找子串,并用新的子串替代
count(“子串”) 返回子串在字符串中出现的次数
大小写转换 upper() 将小写字母转化为大写
lower() 将大写字母转化为小写
swapcase() 将大小写字母反转
去除空格 lstrip() 去除左侧空格
rstrip() 去除右侧空格
strip() 去除左右两侧空格
拆分 split("子串") 根据子串拆分字符串,返回由拆分后字符串组成的 list

字符串[索引]

  • 得到字符串中的值

isalpha()

  • 判断字符串是否为纯字母构成

isdigit()

  • 判断字符串是否为数字构成

islower()

  • 判断字符串中所有字母是否都为小写

isupper()

  • 判断字符串中所有字母是否都为大写
# 定义一个字符串 str1
str1 = "我爱 python"

#得到字符串中的值
print(str1[1])

#判断字符串是否为纯字母构成
if str1.isalpha():
    print("是")
else:
    print("不是")

#判断字符串是否为数字构成
if str1.isdigit():
    print("是")
else:
    print("不是")

#判断字符串中所有字母是否都为小写
if str1.islower():
    print("是")
else:
    print("不是")

#判断字符串中所有字母是否都为大写
if str1.isupper():
    print("是")
else:
    print("不是")

查找和替换:

find()

  • 查找子串在字符串中出现的位置,找不到返回 -1

  • str1.find("p")
    

replace()

  • 替换子串

  • str2=str1.replace("python","world")
    #并不是str1改变了,是吧str1中的Python变为world 给str2了
    

count()

  • 返回子串在字符串中出现的次数

  • str1.count("我爱")
    
# 定义一个字符串 str1
str1 = "我爱 python 我爱"

a=str1.find("p")
print(a)

str2=str1.replace("python","world")
print(str2)

b=str1.count("我爱")
print(b)

3
我爱 world 我爱
2

Process finished with exit code 0

大小写转换:

upper()

  • 将小写字母转化为大写

  • str1.upper()
    

lower()

  • 将大写字母转化为小写

  • str1.lower()
    

swapcase()

  • 将大小写字母反转

  • str1.swapcase()
    
# 定义一个字符串 str1
str1 = "AbCdEf"
print(str1)

str2=str1.upper()
print(str2)

str3=str1.lower()
print(str3)

str4=str1.swapcase()
print(str4)

AbCdEf
ABCDEF
abcdef
aBcDeF

Process finished with exit code 0

去除空格 :

lstrip()

  • 去除左侧空格

rstrip()

  • 去除右侧空格

strip()

  • 去除左右两侧空格
# 定义一个字符串 str1
str1 = "  aaaaa  "
print(str1)

str2=str1.lstrip()
print(str2)

str3=str1.rstrip()
print("'%s'"% str1)
print("'%s'"% str3)

str4=str1.strip()
print(str4)

  aaaaa  
aaaaa  
'  aaaaa  '
'  aaaaa'
aaaaa

Process finished with exit code 0

拆分:

split()

  • 根据子串拆分字符串,返回由拆分后字符串组成的 list
# 定义一个字符串 str1
str1 = "aaaa_bbbb_eee_hello"
list1=str1.split("_")
print(list1)

sql="select * from book"
print(sql.split())
print(sql.split()[0])

['aaaa', 'bbbb', 'eee', 'hello']
['select', '*', 'from', 'book']
select

Process finished with exit code 0

三、字符串课堂练习

1. 课堂练习---

通过 input 函数,输入一个字符串,判断字符串是否可以转化为整数, 
如果不可以转化, 显示"请输入数字"
str1=input("请输入一个整数")  #
str2=input("请输入一个整数")
if str1.isdigit()  and str2.isdigit():
    a=int(str1)
    b=int(str2)
    print(a+b)
else:
    print("请输入数字")

四、格式化字符串

  • % 被称为格式化操作符,专⻔⽤于处理字符串中的格式
  • 包含 % 的字符串,被称为格式化字符串
  • % 和不同的字符连⽤,不同类型的数据需要使⽤不同的格式化字符
格式化字符 说明
%s 字符串
%d 有符号十进制整数,%06d 表示输出 6 位整数,不足用 0 补全
%x 无符号十六进制整数,%06x 表示输出 6 位整数,不足用 0 补全
%X 无符号十六进制整数,用大写字母表达
%f 浮点数,%.2f 表示只显示小数点后两位
%% 输出%
  • 语法格式
str1 = "姓名:%s, 年龄%d" % ("鲁肃", 31)

1、% 和 .format方法进行格式化

语法

"姓名:%s, 年龄:%d" % ("鲁肃", 31)
"姓名:{}, 年龄:{}"  .format("鲁肃",31)
str1 = "姓名:%s, 年龄:%d" % ("鲁肃", 31)  #把格式化字符串的结果,放到str1变量里
print(str1)

str1 = "姓名:{}, 年龄:{}"  .format("鲁肃",31)
print(str1)

姓名:鲁肃, 年龄:31
姓名:鲁肃, 年龄:31

Process finished with exit code 0

2、课堂练习

id = 1 
name = "刘备" 
weight = 80.2 
tel = "13912345678" 
# 以上变量,输出结果如下

********************
编号:000001
姓名:刘备
体重:80.200
电话:18323432123
********************
  • 两种方法
id= 1
name= '刘备'
weight= 80.2
tel='18323432123'

print("*" * 20)
print("编号:%06d" %id)
print("姓名:%s" %name)
print("体重:%.3f" %weight)
print("电话:%s"%tel)
print("*" * 20)

print("编号:{b:06d}" .format(b=id))
print("姓名:{}".format(name))
print("体重:{a:.3f}".format(a=weight) )
print("电话:{}".format(tel))

********************
编号:000001
姓名:刘备
体重:80.200
电话:18323432123
********************
编号:000001
姓名:刘备
体重:80.200
电话:18323432123

Process finished with exit code 0

第 8 章 变量进阶------字符串的切⽚

只要可以使用 [索引] 访问成员的数据类型,都可以用切片

  • 切⽚⽅法适⽤于 ---字符串、列表、元组 ;
  • 切⽚使⽤索引值来限定范围,从⼀个⼤的字符串中切出⼩的字符串 ;
  • 字符串、列表和元组都是有序的集合,都能够通过[索引]获取到对应的数据

一、切片语法

  • 字符串[开始索引:结束索引:步⻓]

注意:

  1. 指定的区间属于左闭右开型 [开始索引, 结束索引) => 开始索引 >= 范围 < 结束索引 从起始位开始,到结束位的前⼀位结束(不包含结束位本身)
  2. 从头开始,开始索引数字可以省略,冒号不能省略
  3. 到末尾结束,结束索引数字可以省略,冒号不能省略
  4. 步⻓默认为 1 ,如果连续切⽚,数字和冒号都可以省略
str1 = "abcdefg"
str2 = str1[2:4:1]
print(str2)

str2 = str1[:4:1]
print(str2)

str2 = str1[2::1]
print(str2)

cd
abcd
cdefg

Process finished with exit code 0
  • 索引的顺序和倒序
    • 在 Python 中不仅⽀持顺序索引,同时还⽀持倒序索引
    • 所谓倒序索引就是从右向左计算索引
  • 最右边的索引值是 -1,依次递减
# 定义一个字符串
str1 =  ["刘备","关羽","张飞","诸葛亮"]
s = str1[-1]
print(s)

诸葛亮

Process finished with exit code 0

二、切片演练

  1. 截取从 2 ~ 5 位置的字符串
# 定义一个字符串
str1 =  "我爱python"
s = str1[2:6]
print(s)

pyth

Process finished with exit code 0
  1. 截取从 2 ~ 末尾的字符串
# 定义一个字符串
str1 =  "我爱python"
s = str1[2:]
print(s)
  1. 截取从开始 ~ 5 位置的字符串
# 定义一个字符串
str1 =  "我爱python"
s = str1[:6]
print(s)
  1. 截取完整的字符串
# 定义一个字符串
str1 =  "我爱python"
s = str1[:]
print(s)
  1. 从开始位置,每隔⼀个字符截取字符串
# 定义一个字符串
str1 =  "我爱python"
s = str1[::2]
print(s)

我pto

Process finished with exit code 0

6.从索引 1 开始,每隔⼀个取⼀个

# 定义一个字符串
str1 =  "我爱python"
s = str1[1::2]
print(s)

7.截取从 2 到末尾 - 1 的字符串

# 定义一个字符串
str1 =  "我爱python"
s = str1[2:-1]
print(s)

pytho

Process finished with exit code 0

8.截取字符串末尾两个字符

# 定义一个字符串
str1 =  "我爱python"
s = str1[-2:]
print(s)

9、字符串的逆序(⾯试题)

# 定义一个字符串
str1 =  "我爱python"
s = str1[::-1]
print(s)

nohtyp爱我

Process finished with exit code 0

10、课堂作业

list1 = ["刘备","关羽","张飞","诸葛亮"]
#1.把列表中的成员名字逆序
list1=list1[::-1]
print(list1)

#2.把列表中每个字符串也逆序   思路:遍历列表,遍历出来每个字符串后nix

index=0 #定义了一个变量叫index 值为0
for i in list1:
    str1=i[::-1]        #str1就是i颠倒后的结果
    list1[index]=str1   #第一次循环的时候list[0]=str1
    index =index+1
    print(str1)
    
['诸葛亮', '张飞', '关羽', '刘备']
亮葛诸
飞张
羽关
备刘
['亮葛诸', '飞张', '羽关', '备刘']

Process finished with exit code 0

11、索引为变量的含义

列表[索引]=值 来修改指定成员的值

索引可以是一个值,也可以是一个变量

list1 = ["刘备","关羽","张飞"]
print(list1)

list1[0]='曹操'
print(list1)

index=2
list1[index]='马超'
print(list1)

['刘备', '关羽', '张飞']
['曹操', '关羽', '张飞']
['曹操', '关羽', '马超']

Process finished with exit code 0

第 9 章 变量进阶------多维列表

一、二维列表

列表中的数据又是另一个列表,有如下列表结构:

用列表存放以上二维表格

# 定义一个二维列表
list1 = [['刘备', 30], ['张飞', 20]]
# list1[0][0]代表第一行第一列的值
print(list1[0][0])
# list1[1][1]代表第二行第二列的值
print(list1[1][1])

刘备
20

Process finished with exit code 0

二、多维列表

python 中不但可以有二维列表,还可以有三维等多维列表,此处不再展开赘述。

posted @ 2022-08-25 17:19  mike002  阅读(99)  评论(0)    收藏  举报