Python 入门之Python基础数据类型

1、 整型:int

用于计算,用于比较 (在赋值的时候先执行等号右边的内容)

1.1 整数的加

a = 10
b = 20
print(a + b)
结果:
30
a = 10
b = 20
print(a + b)
结果:
30

1.2 整数的减

a = 10
b = 20
print(b - a)
结果
10
a = 10
b = 20
print(b - a)
结果
10

1.3 整数的乘

a = 10
b = 20
print(a * b)
结果:
200
a = 10
b = 20
print(a * b)
结果:
200

1.4 整数的除

a = 10
b = 20
print(b / a)
结果:
2.0
# 注意点:当我们使用Python3的时候我们除法获取到时浮点数,也就是小数,但是使用Python2的时候使用除法获取的就是整数
a = 10
b = 20
print(b / a)
结果:
2.0
# 注意点:当我们使用Python3的时候我们除法获取到时浮点数,也就是小数,但是使用Python2的时候使用除法获取的就是整数

1.5 整数的整除

a = 10
b = 20
print(b // a)
结果:
2
a = 10
b = 20
print(b // a)
结果:
2

1.6 整数的取余

a = 5
b = 2
print(a % b)
结果:
1
a = 5
b = 2
print(a % b)
结果:
1

1.7 整数的次方(幂)

a = 5
b = 2
print(a ** b)
结果:
25
a = 5
b = 2
print(a ** b)
结果:
25

(python3除法的时候返回的是小数(浮点数),Python2除法的时候返回的是整数(向下取整))

在32位机器上int的范围是: -231~231-1,即-2147483648~2147483647

在64位机器上int的范围是: -263~263-1,即-9223372036854775808~9223372036854775807

整型在Python2和Python3中的区别:

Python3:全部为整型

Python2:整型,长整型long

1.8 10进制转2进制的转换

1.8.1 10进制转2进制:bin()函数

方法:除2求余,从下往上写

print(bin(30))
print(bin(30))
1.8.2 2进制转10进制:int(“11011101”,2)函数

方法:当前位置上的数乘以2的位数减1次方,并相加即可

print(int("111110",2))
print(int("111110",2))

2、布尔值:bool

true — 真 false — 假 :(用于判断)

print(3 > 2)         # 输出借结果为True
print(3 < 2)        # 输出结果为False
print(3 > 2)         # 输出借结果为True
print(3 < 2)        # 输出结果为False

3、字符串:str

用于存储一些数据,存储少量数据。在Python中只要是用引号引起来就是字符串,字符串中的每一个字母或者字符都称为元素(字符串拼接:字符串+字符串 字符串翻倍:字符串*数字)

a = """absc"""
print(a)
a = """absc"""
print(a)

3.1 字符串加法

#字符串的拼接
s1 = 'a' 
s2 = 'bc'
print(s1 + s2)
#字符串的拼接
s1 = 'a' 
s2 = 'bc'
print(s1 + s2)

3.2 字符串乘法(乘法的规则:只能是字符串和数字相乘)

str*int name = '小强'
print(name*8)
str*int name = '小强'
print(name*8)

字符串中是不能进行减法和除法操作的

3.3 索引(下标):

<1> 从左向右排(正向索引从0开始)

<2> 从右向左排(反向索引从-1开始)

a = "hello_wiu_srr,_taa_ba_hello"
print(a[5])
print(a[6])
print(a[11])
print(a[-2])
print(a[-1])
a = "hello_wiu_srr,_taa_ba_hello"
print(a[5])
print(a[6])
print(a[11])
print(a[-2])
print(a[-1])

索引的时候不能超出索引最大值

3.4 切片:

[起始位置(包含):终止位置(不包含)] :顾头不顾尾

[起始位置:] :从起始默认到最后

[:] :默认从最开始到最后

切片的时候可以超出索引值

a = "hello_wiu_srr,_taa_ba_hello"
print(a[21:100])
print(a[21:])    # [21(起始位置):(默认到最后)]
print(a[:])      # [(默认从最开始):(默认到最后)]
a = "hello_wiu_srr,_taa_ba_hello"
print(a[21:100])
print(a[21:])    # [21(起始位置):(默认到最后)]
print(a[:])      # [(默认从最开始):(默认到最后)]

3.5 步长:

步长决定查找方向,以及查找时迈的步子

切片的时候步长默认为1

正数为正向索引(从左向右),负数为反向索引(从右向左)

在结束位置内:起始位置+步长得到下一字符元素

[::-1] :将字符串反向输出

a = "hello_wiu_srr,_taa_ba_hello"
print(a[1:8:2]) 
print(a[1:8:4]) 

print(a[-12:-3:2])  
print(a[10:-5:1])
print(a[-5:-10:-1])
a = "hello_wiu_srr,_taa_ba_hello"
print(a[1:8:2]) 
print(a[1:8:4]) 

print(a[-12:-3:2])  
print(a[10:-5:1])
print(a[-5:-10:-1])

字符串是不可变数据类型,字符串是有序的

3.6 字符串的方法:

<1> upper() :全部大写

name = "maex"
a = name.upper()  # 全部大写
print(a)
print(name)
name = "maex"
a = name.upper()  # 全部大写
print(a)
print(name)

<2> lower() :全部小写

name = "MAEX"
a = name.lower()   # 全部小写
print(name)
print(a)
name = "MAEX"
a = name.lower()   # 全部小写
print(name)
print(a)

<3> startswith() :以什么开头

name = "maex"
print(name.startswith('e',2,3))  # 以什么开头 -- 返回的是布尔值
name = "maex"
print(name.startswith('e',2,3))  # 以什么开头 -- 返回的是布尔值

<4> endswith() :以什么结尾

name = "maex"
print(name.endswith('l',0,2))    # 以什么结尾 -- 返回的是布尔值
name = "maex"
print(name.endswith('l',0,2))    # 以什么结尾 -- 返回的是布尔值

<5> count() :统计,计数

name = "maexwauisrtaaibbIa"
print(name.count("i"))      # 统计,计数
name = "maexwauisrtaaibbIa"
print(name.count("i"))      # 统计,计数

<6> strip() :脱(脱头尾两端的空格,换行符\n,制表符\t);去除头尾两端指定内容

pwd = " wslexsdsb   "
a = pwd.strip()   # 脱 默认脱(脱头尾两端的空格,换行符\n,制表符\t)
print(a)

pwd = "alxasdsbala"
a = pwd.strip("al")  # 去除头尾两端指定的内容
print(a)
pwd = " wslexsdsb   "
a = pwd.strip()   # 脱 默认脱(脱头尾两端的空格,换行符\n,制表符\t)
print(a)

pwd = "alxasdsbala"
a = pwd.strip("al")  # 去除头尾两端指定的内容
print(a)

<7> split() :分割(默认空格,换行符\n,制表符\t);也可以以指定的元素分割。可以指定分割的次数

name = "allwex_wusu_sdi_r"
a = name.split("_")        # 分割(默认空格,换行符\n,制表符\t)
print(a)                  

print(name.split("_",2))   # 可以指定分割的次数
name = "allwex_wusu_sdi_r"
a = name.split("_")        # 分割(默认空格,换行符\n,制表符\t)
print(a)                  

print(name.split("_",2))   # 可以指定分割的次数

<8> replace() :替换. Replace(“要被替换的内容”,”替换为的内容”,替换次数)

name = "alex,wusir,ta,i,b,a,i"
a = name.replace(",",".")               # 全部替换
print(a)

a = name.replace(",",".",4)              # 可以指定替换的次数
print(a)
name = "alex,wusir,ta,i,b,a,i"
a = name.replace(",",".")               # 全部替换
print(a)

a = name.replace(",",".",4)              # 可以指定替换的次数
print(a)

3.7 字符串格式化:

format() :按照位置顺序进行填充;按照索引填充;按照名字进行新填充

name = "{}今年:{}".format("宝元",18)    # 按照位置顺序进行填充
print(name)

name = "{1}今年:{0}".format("宝元",18)    # 按照索引进行填充
print(name)

name = "{name}今年:{age}".format(name="宝元",age=18)    # 按照名字进行填充
print(name)
name = "{}今年:{}".format("宝元",18)    # 按照位置顺序进行填充
print(name)

name = "{1}今年:{0}".format("宝元",18)    # 按照索引进行填充
print(name)

name = "{name}今年:{age}".format(name="宝元",age=18)    # 按照名字进行填充
print(name)

3.8 is 系列 是进行判断 返回的是布尔值

(1)isdigit() :判断字符串中的内容是不是全都是数字(阿拉伯数字)

msg = "alex"
print(msg.isdigit())      # 判断字符串中的内容是不是全都是数字(阿拉伯数字)
msg = "alex"
print(msg.isdigit())      # 判断字符串中的内容是不是全都是数字(阿拉伯数字)

(2)isdecimal() :判断是不是十进制数

msg = "alex"
print(msg.isdecimal())    # 判断是不是十进制数
msg = "alex"
print(msg.isdecimal())    # 判断是不是十进制数

(3)isalnum() :判断是不是数字,字母,中文

msg = "alex"
print(msg.isalnum())      # 判断是不是数字,字母,中文
msg = "alex"
print(msg.isalnum())      # 判断是不是数字,字母,中文

(4)Isalpha() :判断是不是字母,中文

msg = "alex"
print(msg.isalpha())      # 判断是不是字母,中文
msg = "alex"
print(msg.isalpha())      # 判断是不是字母,中文

3.9 str数据类型方法—补充:

<1> 字符串名.capitalize() :首字母大写

a = "alex Wusir"
print(a.capitalize())   # 首字母大写
a = "alex Wusir"
print(a.capitalize())   # 首字母大写

<2> 字符串名.title() : 每个单词首字母大写

a = "alex Wusir"
print(a.title())        # 每个单词首字母大写
a = "alex Wusir"
print(a.title())        # 每个单词首字母大写

<3> 字符串名.swapcase() : 大小写调换

a = "alex Wusir"
print(a.swapcase())     # 大小写转换
a = "alex Wusir"
print(a.swapcase())     # 大小写转换

<4> 字符串名.center() : 居中 填充

a = "alex Wusir"
print(a.center(20,"*"))     # 居中 - 填充
a = "alex Wusir"
print(a.center(20,"*"))     # 居中 - 填充

<5> 字符串名.find() : 查找 通过元素查找索引,查找不到时返回-1

a = "alex Wusir"
print(a.find("c"))        # 查找 通过元素查找索引,查找不到时返回-1
a = "alex Wusir"
print(a.find("c"))        # 查找 通过元素查找索引,查找不到时返回-1

<6> 字符串名.index() : 查找 通过元素查找索引,查找不到时就报错

a = "alex Wusir"
print(a.index("c"))       # 查找 通过元素查找索引,查找不到时就报错
a = "alex Wusir"
print(a.index("c"))       # 查找 通过元素查找索引,查找不到时就报错

<7> “进行拼接的元素”.join(["1","2","3"]) : 拼接 ,将列表转换成字符串 (int型无法直接进行拼接)

a = "alex Wusir"
print(a.join("_"))

lst = ["1","2","4"]
print("_".join(lst))  # 拼接,将列表转换成字符串
a = "alex Wusir"
print(a.join("_"))

lst = ["1","2","4"]
print("_".join(lst))  # 拼接,将列表转换成字符串

<8>str + str

name1 = "al"
name2 = "au"
print(id(name1))
print(id(name2))
print(id(name1 + name2))
name1 = "al"
name2 = "au"
print(id(name1))
print(id(name2))
print(id(name1 + name2))

<9>str * 数字

name1 = "al"
print(id(name1))
print(id(name1 * 5))
name1 = "al"
print(id(name1))
print(id(name1 * 5))

(字符串进行加操作,乘操作都是开辟新的空间)

4、列表:list

列表是Python中的数据类型之一,能够存储大量的不同类型的数据。在别的语言中称为数组。32位python的限制是 536870912 个元素,64位python的限制是 1152921504606846975 个元素。而且列表是有序的,有索引值,可切片,方便取值

4.1 定义一个列表: lst = [ ]

lst = [1,2,"alex",True,["钥匙","门禁卡",["银行卡"]]]
print(lst)
lst = [1,2,"alex",True,["钥匙","门禁卡",["银行卡"]]]
print(lst)

列表 --- 容器

列表是一种有序的容器, 支持索引

列表是一种可变的数据类型 原地修改

列表中以逗号分割开的才是一个元素

4.2 列表的索引

列表和字符串一样也拥有索引:

lst = ['刘德华','周润发','周杰伦','向华强']
print(lst[0])  # 列表中第一个元素
print(lst[1])  # 列表中第二个元素
print(lst[2])  # 列表中第三个元素
lst = ['刘德华','周润发','周杰伦','向华强']
print(lst[0])  # 列表中第一个元素
print(lst[1])  # 列表中第二个元素
print(lst[2])  # 列表中第三个元素

注意:列表是可以进行修改的,这里和字符串不一样

lst[3] = '王健林'
print(lst)
lst[3] = '王健林'
print(lst)

字符串修改

s = '王思聪'
s[0] = '李'
print(s)
结果:
Traceback (most recent call last):
  File "D:/python_object/path2/test.py", line 1076, in <module>
    s[0] = '李'
TypeError: 'str' object does not support item assignment
s = '王思聪'
s[0] = '李'
print(s)
结果:
Traceback (most recent call last):
  File "D:/python_object/path2/test.py", line 1076, in <module>
    s[0] = '李'
TypeError: 'str' object does not support item assignment

4.3 列表的切片

lst = ["麻花藤", "王剑林", "马芸", "周鸿医", "向华强"] 
print(lst[0:3])     # ['麻花藤', '王剑林', '马芸'] 
print(lst[:3])      # ['麻花藤', '王剑林', '马芸']
print(lst[1::2])    # ['王剑林', '周鸿医'] 也有步长 
print(lst[2::-1])   # ['马芸', '王剑林', '麻花藤'] 也可以倒着取 
print(lst[-1:-3:-2])    # 倒着带步长
lst = ["麻花藤", "王剑林", "马芸", "周鸿医", "向华强"] 
print(lst[0:3])     # ['麻花藤', '王剑林', '马芸'] 
print(lst[:3])      # ['麻花藤', '王剑林', '马芸']
print(lst[1::2])    # ['王剑林', '周鸿医'] 也有步长 
print(lst[2::-1])   # ['马芸', '王剑林', '麻花藤'] 也可以倒着取 
print(lst[-1:-3:-2])    # 倒着带步长

4.4 列表的增加:

<1> append() :追加 在最末尾的地方进行添加 append(追加的内容)

lst = [1,2,3,4,3]
lst.append(13)   # 追加  在最末尾的地方进行添加print(lst)
lst = [1,2,3,4,3]
lst.append(13)   # 追加  在最末尾的地方进行添加print(lst)

<2> insert() :插入 insert(插入的位置,“插入的内容”) 尽量减少使用,会使效率下降

lst = [1,2,3,4,3]
lst.insert(2,"ro")       # 插入
print(lst)
lst = [1,2,3,4,3]
lst.insert(2,"ro")       # 插入
print(lst)

<3> extend() :迭代添加 一个一个添加

lst = [1,2,3,4,3]
lst.extend([1,2,3,4])       # 迭代添加(一个一个添加)
print(lst)
lst = [1,2,3,4,3]
lst.extend([1,2,3,4])       # 迭代添加(一个一个添加)
print(lst)

4.5 列表的删除:

<1> remove() :只能删除一个,从左向右删除。通过元素的名字进行删除

lst = [1,2,3,4,3]
list.remove(1)    
print(lst)
lst = [1,2,3,4,3]
list.remove(1)    
print(lst)

<2> pop() :弹出 默认删除最后一个,并且具有返回值,返回值为弹出的那个。也可以加下标进行删除pop(3)。Repr() :查看当前数据的源生态

lst = [1,2,3,4,3]
print(repr(lst.pop(2)))    # repr()查看当前数据的原生态
print(lst)
lst = [1,2,3,4,3]
print(repr(lst.pop(2)))    # repr()查看当前数据的原生态
print(lst)

<3>clear() :清空

lst = [1,2,3,4,3]
lst.clear()             # 清空
print(lst)
lst = [1,2,3,4,3]
lst.clear()             # 清空
print(lst)

<4> del() :直接在内存空间中删除。可通过索引,切片,步长删除

lst = [1,2,3,4,3]
del lst[4]    # 通过索引删除
del lst[2:5]    # 通过切片删除
del lst[1:5:2]      # 通过步长删除
print(lst)
lst = [1,2,3,4,3]
del lst[4]    # 通过索引删除
del lst[2:5]    # 通过切片删除
del lst[1:5:2]      # 通过步长删除
print(lst)

4.6 列表的修改:

<1> lst[2] = 80 :通过索引进行修改

lst = [1,2,3,4,5]
lst[2] = 80    # 通过索引进行修改
print(lst))
lst = [1,2,3,4,5]
lst[2] = 80    # 通过索引进行修改
print(lst))

<2> Lst[1:3] = “skaj” :通过切片进行修改,必须是可迭代的对象。默认步长为1,修改的内容可多可少

lst = [1,2,3,4,5]
lst[1:3] = "20"  # 通过切片进行修改,默认步长为1,修改的内容必须是可迭代的对象,修改的内容可多可少
print(lst)
lst = [1,2,3,4,5]
lst[1:3] = "20"  # 通过切片进行修改,默认步长为1,修改的内容必须是可迭代的对象,修改的内容可多可少
print(lst)

<3> Lst[1:5:2] = “10” :通过步长进行修改,步长不为1的时候,必须一一对应

lst = [1,2,3,4,5]
lst[1:5:2] = 100,100    # 步长不为1的时候,必须一一对应print(lst)
lst = [1,2,3,4,5]
lst[1:5:2] = 100,100    # 步长不为1的时候,必须一一对应print(lst)

4.7 列表的查找:

<1> 通过索引进行查找

<2> for循环

lst = [1,2,3,4,5]
    for i in lst:
        print(i)
lst = [1,2,3,4,5]
    for i in lst:
        print(i)

4.8 列表的嵌套:

lst = [1,2,[3,4,5,["alex[]",True,[[1,2,]],90],"wusir"],"taibai"]
lst1 = lst[2]   # [3, 4, 5, ['alex[]', True, [[1, 2]], 90], 'wusir']
lst2 = lst1[3]  # ['alex[]', True, [[1, 2]], 90]
str_1 = lst2[0]
print(str_1[-1])
print(lst[2][3][0][-1])
lst = [1,2,[3,4,5,["alex[]",True,[[1,2,]],90],"wusir"],"taibai"]
lst1 = lst[2]   # [3, 4, 5, ['alex[]', True, [[1, 2]], 90], 'wusir']
lst2 = lst1[3]  # ['alex[]', True, [[1, 2]], 90]
str_1 = lst2[0]
print(str_1[-1])
print(lst[2][3][0][-1])

一层一层的查找,[……]视为一个元素

4.9 list数据类型方法—补充:

<1> 列表的定义:list(“123456”)

<2> 列表的方法:

1> 列表名.index() : 通过元素查找索引
lst = [1,23,4,5,7,8,9]
print(lst.index(4))        # 通过元素查找索引
lst = [1,23,4,5,7,8,9]
print(lst.index(4))        # 通过元素查找索引
2> 列表名.reverse() : 反转
lst = [1,23,4,5,7,8,9]
lst.reverse()     
print(lst)
lst = [1,23,4,5,7,8,9]
lst.reverse()     
print(lst)
3> 列表名.sort() : 排序 默认是升序
lst = [1,23,4,5,7,8,9]
lst.sort()                 # 排序 默认是升序
print(lst)
lst = [1,23,4,5,7,8,9]
lst.sort()                 # 排序 默认是升序
print(lst)
4> 列表名.sort(reverse=True) : 降序
lst = [1,23,4,5,7,8,9]
lst.sort(reverse=True)     # 降序
print(lst)
lst = [1,23,4,5,7,8,9]
lst.sort(reverse=True)     # 降序
print(lst)

试题:

lst = [1,[]] * 5
 print(lst)       # [1, [], 1, [], 1, [], 1, [], 1, []]
 lst[1].append(6)
 print(lst)       # [1, [6], 1, [6], 1, [6], 1, [6], 1, [6]]
lst = [1,[]] * 5
 print(lst)       # [1, [], 1, [], 1, [], 1, [], 1, []]
 lst[1].append(6)
 print(lst)       # [1, [6], 1, [6], 1, [6], 1, [6], 1, [6]]
列表在进行乘法的时候,元素是共用的

5、元组:tuple

元组是Python中的数据类型之一,它是有序的,不可变的,只支持查询。元组就是一个不可变的列表。

5.1 定义方式: Tu = (1,2,3)

tu = (1,2,"alex",[1,3,4])
print(tu)
tu = (1,2,"alex",[1,3,4])
print(tu)

5.2元组的统计:

元组.count()

tu = (1,2,3,4,5,1,2,1)
print(tu.count(1))
tu = (1,2,3,4,5,1,2,1)
print(tu.count(1))

5.3 元组的获取索引:

元组.index(4) :通过元素查询索引

tu = (1,2,3,4,5,1,2,1)
print(tu.index(2))  # 通过元素查询索引
tu = (1,2,3,4,5,1,2,1)
print(tu.index(2))  # 通过元素查询索引

5.4 元组的用途:

配置文件中使用

5.5 元组的嵌套:

tu = (1,2,3,4,(5,6,7,8,("alex","wusir",[1,23,4])))
print(tu[4][4][0])
tu = (1,2,3,4,(5,6,7,8,("alex","wusir",[1,23,4])))
print(tu[4][4][0])

(3)Tuple:

试题:

tu = (1)
     \# tu1 = ("alex")
     \# tu2 = (1,)          #元组
  tu = (1)
     \# tu1 = ("alex")
     \# tu2 = (1,)          #元组

5.6 tuple数据类型方法—补充:

<1> tu + tu

tu = (12,3,4) + (4,5,3,4)
print(tu)
tu = (12,3,4) + (4,5,3,4)
print(tu)

<2> tu * 数字

tu = (1,[]) * 3
print(tu)
tu[-1].append(10)
print(tu)
tu = (1,[]) * 3
print(tu)
tu[-1].append(10)
print(tu)
元组在进行乘法的时候,元素是共用的

6、字典 – dict

字典是Python的中的数据结构之一,是一种无序的,可变的数据类型,字典中的所有操作都是通过键。

6.1 定义: dic = {“key”:”value”} --- 键值对

6.2 字典的作用:

存储大大量数据,将数据和数据起到关联作用

dic = {"10":"苹果手机",
       "11":"苹果手机",
       15:"小米手机",
       15:"华为手机",
       (1,):"oppo手机",
       }
print(dic)
dic = {"10":"苹果手机",
       "11":"苹果手机",
       15:"小米手机",
       15:"华为手机",
       (1,):"oppo手机",
       }
print(dic)
键:必须是不可变的数据类型(可哈希),且唯一
值:任意,可变(不可哈希)

6.3 字典的增:

<1> 暴力添加:

dic[“ 键”] = “值” //字典的添加,添加的是一个键值对
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
dic["日阳"] = "小明"  # 字典的添加,添加的是一个键值对
dic["小妹"] = ["听歌","唱歌","吃","烤馕","大盘鸡","葡萄干"]
print(dic)
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
dic["日阳"] = "小明"  # 字典的添加,添加的是一个键值对
dic["小妹"] = ["听歌","唱歌","吃","烤馕","大盘鸡","葡萄干"]
print(dic)
<2> dic.setdefault(“键”,[“值1”,”值2”] //有则不添加,无则添加:
先查看键是否存在字典
不存在的时候进行添加
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
dic.setdefault("元宝",["唱","跳","篮球","喝酒"])
print(dic)
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
dic.setdefault("元宝",["唱","跳","篮球","喝酒"])
print(dic)

6.4 字典的删除:

<1> pop() : //pop删除通过字典中的键进行删除,返回的也是被删除的值

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
print(dic.pop("宝元"))  #pop删除通过字典中的键进线删除 返回的也是被删除的值
print(dic)
dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
print(dic.pop("宝元"))  #pop删除通过字典中的键进线删除 返回的也是被删除的值
print(dic)

<2> clear() : //清空

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
dic.clear()      # 清空
print(dic)
dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
dic.clear()      # 清空
print(dic)

<3> del dic: //删除的是整个字典容器

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
del dic          # 删除的是整个容器
print(dic)
dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
del dic          # 删除的是整个容器
print(dic)

<4> del dic[“键”] : //通过键进行删除

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
del dic["alex"]  # 通过键进行删除
print(dic)
dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }
del dic["alex"]  # 通过键进行删除
print(dic)
字典中没有remove

6.5 字典的改:

<1> dic[“键”] = “值” : //有则就覆盖,没有就添加

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }

dic["alex"] = "dsb"   # 有则就覆盖,没有添加
print(dic)
dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }

dic["alex"] = "dsb"   # 有则就覆盖,没有添加
print(dic)

<2> update(新字典) : //update函数后面的字典级别高于前面的字典

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }

dic1 = {"alex":"上过北大","wusir":"干过前端"}
dic1.update(dic)
print(dic1)

dic = {
              "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
              "炮手":"飞机",
              "豹哥":"贴膏药",
              "宝元":"宝剑",
              "alex":"吹牛逼"
       }

dic1 = {"alex":"上过北大","wusir":"干过前端"}
dic1.update(dic)
print(dic1)

6.6 字典的查:

<1> get (”键”) : //查询不到时返回None get(“键”,”自己指定的内容”):当查询不到时返回自己指定的内容

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic.get("alex"))   # 查询不到返回None
print(dic.get("元宝","找不到啊")) # 查找不到的时候返回自己制定的内容

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic.get("alex"))   # 查询不到返回None
print(dic.get("元宝","找不到啊")) # 查找不到的时候返回自己制定的内容

<2> setdefault(“键”) : // 查询不到时返回None

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic.setdefault("alex"))  # 查询不到返回None

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic.setdefault("alex"))  # 查询不到返回None

<3> dic[“键”] : //查询不到就报错

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic["alex"])       # 查询不到就报错了

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

print(dic["alex"])       # 查询不到就报错了

<4> dic.keys() : //查看键 获取到的是一个高仿列表

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

for i in dic:   # 查看所有的键
    print(i)

print(dic.keys())   # 获取到的是一个高仿列表
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

for i in dic:   # 查看所有的键
    print(i)

print(dic.keys())   # 获取到的是一个高仿列表

<5> dic.values() : //查看值, 获取到的是一个高仿列表

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

for i in dic:   # 查看所有的值
    print(dic.get(i))

print(dic.values()) # 获取到的是一个高仿列表
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}

for i in dic:   # 查看所有的值
    print(dic.get(i))

print(dic.values()) # 获取到的是一个高仿列表

高仿列表支持迭代,不支持索引

for i in dic.values(): # 高仿列表支持迭代
    print(i)
for i in dic.values(): # 高仿列表支持迭代
    print(i)

<6> items() : //查看键值对

dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
for i in dic.items():
    print(i[0],i[1])
dic = {
       "日魔":["看动漫","健身","吃包子","吃大煎饼","吃大烧饼"],
       "炮手":"飞机",
       "豹哥":"贴膏药",
       "宝元":"宝剑",
       "alex":"吹牛逼"
}
for i in dic.items():
    print(i[0],i[1])

6.7 字典的嵌套:

字典嵌套查找的时候一定是按照一层一层进行查找

dic = {

    101:{1:{"日魔":"对象"},
         2:{"隔壁老王":"王炸"},
         3:{"乔碧萝":("日魔","炮手","宝元")},
         },
    102:{1:{"汪峰":{"国际章":["小苹果","大鸭梨"]}},
         2:{"邓紫棋":["泡沫","信仰","天堂","光年之外"]},
         3:{"腾格尔":["隐形的翅膀","卡路里","日不落"]}
         },
    103:{1:{"蔡徐坤":{"唱":["鸡你太美"],
                   "跳":["钢管舞"],
                   "rap":["大碗面"],
                   "篮球":("NBA形象大使")}},

         2:{"JJ":{"行走的CD":["江南","曹操","背对背拥抱","小酒窝","不潮不花钱"]}},
         3:{"Jay":{"周董":["菊花台","双节棍","霍元甲"]}}},

    201:{
        1:{"韦小宝":{"双儿":"刺客","建宁":{"公主":{"吴三桂":"熊"}},"龙儿":{"教主老婆":"教主"}}}
    }
}

print(dic[201][1]["韦小宝"]["建宁"]["公主"]["吴三桂"])
print(dic[103][1]["蔡徐坤"]["跳"][0][1])
print(dic[102][2]["邓紫棋"][1])

dic = {

    101:{1:{"日魔":"对象"},
         2:{"隔壁老王":"王炸"},
         3:{"乔碧萝":("日魔","炮手","宝元")},
         },
    102:{1:{"汪峰":{"国际章":["小苹果","大鸭梨"]}},
         2:{"邓紫棋":["泡沫","信仰","天堂","光年之外"]},
         3:{"腾格尔":["隐形的翅膀","卡路里","日不落"]}
         },
    103:{1:{"蔡徐坤":{"唱":["鸡你太美"],
                   "跳":["钢管舞"],
                   "rap":["大碗面"],
                   "篮球":("NBA形象大使")}},

         2:{"JJ":{"行走的CD":["江南","曹操","背对背拥抱","小酒窝","不潮不花钱"]}},
         3:{"Jay":{"周董":["菊花台","双节棍","霍元甲"]}}},

    201:{
        1:{"韦小宝":{"双儿":"刺客","建宁":{"公主":{"吴三桂":"熊"}},"龙儿":{"教主老婆":"教主"}}}
    }
}

print(dic[201][1]["韦小宝"]["建宁"]["公主"]["吴三桂"])
print(dic[103][1]["蔡徐坤"]["跳"][0][1])
print(dic[102][2]["邓紫棋"][1])

6.8 dict数据类型方法—补充:

<1> 字典名.popitem() :随机删除,并返回的是被删除的键值对 Python3.6版删除最后一个键值对

dic = {"key":1,"key1":2,"key2":4,"key3":1}
print(dic.popitem())   # 随机删除  python3.6版删除最后一个键值对    # popitem返回的是被删除的键值对
print(dic)
dic = {"key":1,"key1":2,"key2":4,"key3":1}
print(dic.popitem())   # 随机删除  python3.6版删除最后一个键值对    # popitem返回的是被删除的键值对
print(dic)

<2> 字典名.fromkeys(“abc”,[]) : 批量创建键值对“a”:[],“b”:[],“c”:[]

试题:

dic = {}
     dic.fromkeys("abc",[])   # 批量创建键值对 
     print(dic)
dic = {}
     dic.fromkeys("abc",[])   # 批量创建键值对 
     print(dic)
fromkeys第一个参数必须是可迭代的对象,会将可迭代的对象进行迭代,成为字典的键。第二个参数是值(这个值是共用的)
fromkeys共用的值是可变数据类型就会有坑,不可变数据类型就没事
dic = {}
dic = dic.fromkeys("abc",[])
print(dic)
dic["b"] = 11
dic["a"].append(10)
print(dic)
dic = {}
dic = dic.fromkeys("abc",[])
print(dic)
dic["b"] = 11
dic["a"].append(10)
print(dic)

7、集合:set

集合是Python中的数据类型之一,是无序的,可变的且唯一。集合就是一个没有值的字典,集合天然去重。

试题:用一行代码去重

lst = [1,223,1,1,2,31,231,22,12,3,14,12,3]
print(list(set(lst)))
lst = [1,223,1,1,2,31,231,22,12,3,14,12,3]
print(list(set(lst)))

7.1 定义一个空集合 : set1 = set{}

7.2 集合的增:

<1> 集合名.add()

s = set()
s.add("alex")
print(s)
s = set()
s.add("alex")
print(s)

<2> 集合名.update() : 迭代添加

s = set()
s.update("wusir")  # 迭代添加
print(s)
s = set()
s.update("wusir")  # 迭代添加
print(s)

7.3 集合的删:

<1 >集合名.remove() :通过元素删除

s = {100,0.1,0.5,1,2,23,5,4}
s.remove(4)    # 通过元素删除
print(s)
s = {100,0.1,0.5,1,2,23,5,4}
s.remove(4)    # 通过元素删除
print(s)

<2> 集合名.clear() : 清空

s = {100,0.1,0.5,1,2,23,5,4}
s.clear()  # 清空
print(s)
s = {100,0.1,0.5,1,2,23,5,4}
s.clear()  # 清空
print(s)

<3>集合名.pop() : 随即删除(一般情况下是最小的)

s = {100,0.1,0.5,1,2,23,5,4}
s.pop()      # 随机删除 (一般是最小的)
print(s)
s = {100,0.1,0.5,1,2,23,5,4}
s.pop()      # 随机删除 (一般是最小的)
print(s)

7.4 集合的改:

先删后加

s = {1,2,3,4,5}              # 先删后加
s = {1,2,3,4,5}              # 先删后加

7.5 集合的查:

for循环

7.6 集合的其他操作:

(1)差集 -

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s - s1)
print(s1 - s)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s - s1)
print(s1 - s)

(2)交集 &

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s & s1)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s & s1)

(3)并集 |

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s | s1)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s | s1)

(4)反交集 ^

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s ^ s1)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s ^ s1)

(5)子集 < : 返回的是一个布尔值

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s < s1)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s < s1)

(6)父集(超级) > :

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s1 > s)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

print(s1 > s)

(7)冻结集合 frozenset

s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

dic = {frozenset({1,23,4,5}):123}
print(dic)
s = {1,23,9,4,5,7}
s1 = {1,2,3,4,5}

dic = {frozenset({1,23,4,5}):123}
print(dic)