【Python】存储类型都有那些,例子学习

python中的存储类型

1.列表

>>> [1,2,3,4,5,'Curry']
[1, 2, 3, 4, 5, 'Curry']
>>> test=[1,2,3,4,5,'Curry']
>>> print(test)
[1, 2, 3, 4, 5, 'Curry']
>>> for i in test:
	print(i)

1
2
3
4
5
Curry

1.下标

​ 下标就是列表中对应数值的位置,在计算机世界里数字是从0开始的,所以我们的下标也是从0开始计数的。

列表:   [1,2,3,4,5,'curry']
对应下标:[0,1,2,3,4,   5]

2.切片

​ 切片的作用就是将列表内的内容,根据自己的需求来进行截取出来

>>> print(test[0:3])
[1, 2, 3]
>>> print(test[1])
2
>>> print(test[:])
[1, 2, 3, 4, 5, 'Curry']
>>> print(test[1:])
[2, 3, 4, 5, 'Curry']
>>> print(test[:3])
[1, 2, 3]
>>> print(test[::1])
[1, 2, 3, 4, 5, 'Curry']
>>> print(test[::3])
[1, 4]
>>> print(test[::2])
[1, 3, 5]
>>> print(test[1::2])
[2, 4, 'Curry']

3.增删改查

1.增加

append():添加单个元素

extend():添加多个元素

>>> heros=['钢铁侠','蜘蛛侠','绿巨人']
>>> heros.append('黑豹')
>>> print (heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹']
>>> heros.extend(['灭霸','雷神'])
>>> print (heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹', '灭霸', '雷神']
2.切片式添加内容
>>> heros[len(heros):] = ['唐三']
>>> print (heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹', '灭霸', '雷神', '唐三']
>>> heros[len(heros):]=['张三','李四']
>>> print(heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹', '灭霸', '雷神', '唐三', '张三', '李四']
3.插入

insert():插入元素

​ 格式:insert(下标位置,插入元素)

>>> s = [1,2,3,4,5]
>>> s.insert(5,6)
>>> print (s)
[1, 2, 3, 4, 5, 6]
>>> s.insert(0,0)
>>> print (s)
[0, 1, 2, 3, 4, 5, 6]
>>> s.insert(len(s),7)
>>> print(s)
[0, 1, 2, 3, 4, 5, 6, 7]
4.删除

remove():删除单个元素,如果列表内存在多个重复内容,则删除下标位置最近的一个

pop():根据下标位置删除

clear():清空列表所有内容

>>> print (heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹', '灭霸', '雷神', '唐三', '张三', '李四']
>>> heros.remove('张三')
>>> print (heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹', '灭霸', '雷神', '唐三', '李四']
>>> heros.pop(len(heros)-1)
'李四'
>>> print (heros)
['钢铁侠', '蜘蛛侠', '绿巨人', '黑豹', '灭霸', '雷神', '唐三']
>>> heros.clear()
>>> print(heros)
[]
5.改

​ 根据列表的下标进行元素替换

>>> heros=['猪猪侠','菲菲','小呆呆']
>>> heros[0]='juju-bay'
>>> print (heros)
['juju-bay', '菲菲', '小呆呆']
>>> heros[:2]=['超人强','肥波']
>>> print (heros)
['超人强', '肥波', '小呆呆']

​ 根据大小进行排序

​ 使用sort函数可以直接将列表内的内容排序

>>> nums=[3,2,4,5,2,1,4,5,6,7,8]
>>> nums.sort()
>>> nums
[1, 2, 2, 3, 4, 4, 5, 5, 6, 7, 8]
>>> nums.reverse()
>>> nums
[8, 7, 6, 5, 5, 4, 4, 3, 2, 2, 1]
>>> nums=[3,2,4,5,2,1,4,5,6,7,8]
>>> nums.sort(reverse=True)
>>> nums
[8, 7, 6, 5, 5, 4, 4, 3, 2, 2, 1]
6.查

​ index():查询元素的下标

​ count():查询元素在列表中出现的次数

//查元素的下标
>>> print (heros)
['超人强', '肥波', '小呆呆']
>>> heros.index('小呆呆')
2
>>> heros[heros.index('小呆呆')]='菲菲'
>>> heros
['超人强', '肥波', '菲菲']

//查元素的数量
>>> nums.count(2)
2
>>> nums
[8, 7, 6, 5, 5, 4, 4, 3, 2, 2, 1]
7.拷贝列表

​ copy():复制列表

>>> heros_1=heros.copy()
>>> heros_1
['超人强', '肥波', '菲菲']

//切片拷贝列表
>>> heros_2=heros[:]
>>> heros_2
['超人强', '肥波', '菲菲']

2.二维列表

>>> test=[[1,2,3],['a','b','c'],['A','B','C']]
>>> print (test[0][2])
3
>>> print (test[2][0])
A

创建一个二维列表

>>> A = [0]*3
>>> print (A)
[0, 0, 0]
>>> for i in range(3):
	A[i]=[0] * 3

	
>>> print (A)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]


di'er'zhon
>>> A = [[0]*3 for i in range(3)]
>>> print (A)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

3.拷贝列表类型

1.浅拷贝

​ 一维列表的浅拷贝:可以发现当b赋予了a的值,对a的值做出了改变,b的值也随着改变,这就叫做浅拷贝

>>> a=[1,2,3]
>>> b=a
>>> a[1]=4
>>> print (b)
[1, 4, 3]

​ 二维列表浅拷贝:

>>> a=[[1,2,3],[1,2,3]]
>>> b=a.copy()
>>> a[1][1]=4
>>> print(a)
[[1, 2, 3], [1, 4, 3]]
>>> print(b)
[[1, 2, 3], [1, 4, 3]]

2.深拷贝

​ 一维列表的深拷贝:可以发现当b赋予了a的值,对a的值做出了改变,b的值没有改变,这就叫做深拷贝

>>> a=[1,2,3]
>>> b=a.copy()
>>> a[1]=4
>>> print (a)
[1, 4, 3]
>>> print (b)
[1, 2, 3]

​ 二维列表的深拷贝:需要调用copy模块中的deepcopy方法

>>> a=[[1,2,3],[1,2,3]]
>>> import copy
>>> b=copy.deepcopy(a)
>>> a[1][1]=4
>>> print(a)
[[1, 2, 3], [1, 4, 3]]
>>> print(b)
[[1, 2, 3], [1, 2, 3]]

4.列表推导式

一维列表:

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

同等于

>>> oho = [1,2,3,4,5]
>>> oho=[i*2 for i in oho]
>>> print (oho)
[2, 4, 6, 8, 10]

二维列表:

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

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

列表推导式第二种写法:

//创建一个二维列表
>>> S = [[0]*3 for i in range(3)]
>>> print (S)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
//一维列表
>>> even = [i for i in range(10) if i % 2 == 0]
>>> print (even)
[0, 2, 4, 6, 8]

将二维列表降级为一维列表

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

推导式的嵌套判断写法:

>>> [[x,y] for x in range(10) if x % 2 ==0 for y in range(10) if y % 3 == 0]
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]

同等与下面

>>> for i in range(10):
	if i % 2 == 0:
		for j in range(10):
			if j % 3 == 0:
				_.append([i,j])

				
>>> print (_)
[[0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9], [0, 0], [0, 3], [0, 6], [0, 9], [2, 0], [2, 3], [2, 6], [2, 9], [4, 0], [4, 3], [4, 6], [4, 9], [6, 0], [6, 3], [6, 6], [6, 9], [8, 0], [8, 3], [8, 6], [8, 9]]

5.元组

列表:[元素1,元素2,元素3]
元组:(元素1,元素2,元素3)

​ 列表与元组的区别:列表中的值是可以被改变的,但是元组被创建之后,将不可以再改变其中的值

>>> A = (1,2,3)
>>> type (A)
<class 'tuple'>
>>> A.count(1)
1
>>> A.index(1)
0
>>> len(A)
3

​ 冷知识:
​ 当元组中的值变成了列表,列表中的值是可以被改变的

>>> A = ([1,2,3],[1,2,3])
>>> A
([1, 2, 3], [1, 2, 3])
>>> A[0][0] = 0
>>> A
([0, 2, 3], [1, 2, 3])

6.字符串

1.字母方法:

​ .casefold():将字母全部小写

​ .title():将首字母大写

​ .swapcase():将首字母小写,其余字母大写

​ .upper():将所有字母大写

​ .lower():将所有字母小写

>>> x = 'I Love Curry'
>>> x.casefold()
'i love curry'
>>> x.title()
'I Love Curry'
>>> x.swapcase()
'i lOVE cURRY'
>>> x.upper()
'I LOVE CURRY'
>>> x.lower()
'i love curry'

2.格式对其方法:

​ .center():中间对其

​ .ljust():左对其

​ .rjust():右对其

>>> x.center(10)
'I Love Curry'
注意:大小需要大于当前字符串的长度,要么无效

>>> x.center(20)
'    I Love Curry    '
>>> x.ljust(20)
'I Love Curry        '
>>> x.rjust(20)
'        I Love Curry'
>>> x.rjust(20,"#")
'########I Love Curry'

3.查找方法

​ .count():查找当前字符在字符串中出现的次数

​ .find():查找当前字符的下标位置

​ .rfind():查找从右来查找字符的下标位置

>>> x="上海自来水来自海上"
>>> x.count("海")
2
>>> x.count("海",0,5)
1
>>> x.find("海")
1
>>> x.rfind("海")
7

//如果搜索的字符不存在就返回-1
>>> x.find("curry")
-1

4.替换方法

​ 将空格替换成tab

>>> code="""
	print
    print
    """
>>> new_code = code.expandtabs(4)
>>> print (new_code)

    print
    print

将旧的字符进行替换

​ 格式:maketrans(“旧的字符”,“新的字符”,“忽略的字符”)


>>> "no love you".replace("no","yes")
'yes love you'
>>> table = str.maketrans("ABC","123")
>>> "Curry".translate(table)
'3urry'

同等与上一种	

>>> "Curry".translate(str.maketrans("ABC","123"))
'3urry'
>>> "Curry".translate(str.maketrans("ABC","123","rr"))
'3uy'

5.判断与检测

>>> x='i love pythen'
>>> x.startswith('i')
True
>>> x.endswith('pythen')
True
>>> s.startswith('i',1)
>>> x.startswith('i',1)
False
>>> x.startswith('i',0)
True
>>> x.endswith('love',0,6)
True

元组判断多个字符
>>> if x.startswith(("i","we","you")):
	print("yes")
    
yes

对字符串进行判断

>>> x.istitle() //字母开头大写
False
>>> x.isupper() //所有字母大写
False
>>> x.upper().isupper()
True

>>> x.isalpha() //字符串中是否都为字符,空格不算
False
>>> "love".isalpha()
True

使用keyword模块,可以测试该字符串是否是python中的命令

>>> import keyword
>>> keyword.iskeyword("if")
True
>>> keyword.iskeyword("py")
False

对字符串中的数字进行匹配

​ .isnumeric():可以判断多种类型的数字

>>> x='123'
>>> x.isdecimal()
True
>>> x.isdigit()
True
>>> x.isnumeric()
True
>>> x="ⅠⅡⅢ"
>>> x.isdecimal()
False
>>> x.isdigit()
False
>>> x.isnumeric()
True
>>> x="一二三"
>>> x.isdecimal()
False
>>> x.isdigit()
False
>>> x.isnumeric()
True

6.截取方法

​ lstrip(chars:None)

​ rstrip(chars:None)

​ strip(chars:None)

>>> "   左侧不要有空白".lstrip()
'左侧不要有空白'
>>> "右侧不要有空白   ".rstrip()
'右侧不要有空白'
>>> "   两侧不要空白   ".strip()
'两侧不要空白'

截取字符串

​ .lstrip():从左开始

​ .rstrip():从右开始

​ .strip():从两侧开始

>>> "www.baidu.com".lstrip("w.")
'baidu.com'
>>> "www.baidu.com".rstrip("com.")
'www.baidu'
>>> "www.baidu.com".strip("wcom.")
'baidu'

7.拆分和拼接

​ 格式:.split(“分割字符”,位置)

​ .rsplit():从右开始进行分割

​ .splitlines():可以根据转义符来进行拆分

>>> "www.baidu.com".partition(".")
('www', '.', 'baidu.com')
>>> "www/baidu/com".partition("/")
('www', '/', 'baidu/com')
>>> "www baidu com".split()
['www', 'baidu', 'com']
>>> "www,baidu,com".rsplit(",")
['www', 'baidu', 'com']
>>> "www,baidu,com".rsplit(",",1)
['www,baidu', 'com']
>>> "www,baidu,com".split(",",1)
['www', 'baidu,com']
>>> "www\nbaidu\ncom".split("\n")
['www', 'baidu', 'com']
>>> "www\nbaidu\n\rcom".splitlines()
['www', 'baidu', '', 'com']
>>> "www\nbaidu\r\ncom".splitlines()
['www', 'baidu', 'com']

拼接

​ 速度极快

>>> ".".join(["www","baidu","com"])
'www.baidu.com'
>>> "^".join(("A","B","C"))
'A^B^C'

8.字符串的格式化

>>> year = 2010
>>> "今年是{}".format(year)
'今年是2010'
>>> "1+2={},2的平方{},3的立方{}".format(1+2,2*2,3*3*3)
'1+2=3,2的平方4,3的立方27'
>>> "{1}在前,{0}在后".format("0","1")
'1在前,0在后'
>>> "{0}在前,{1}在后".format("0","1")
'0在前,1在后'
>>> "{0}{0}{1}{1}".format("开","心")
'开开心心'
>>> "我叫{name},我爱{0},我最爱{0}".format("python",name="curry")
'我叫curry,我爱python,我最爱python'
>>> "{},{
    
    {}},{}".format(1,2)
'1,{},2'
>>> "{:x} {:-}".format(520,250)
'208 250'
>>> "{:+} {:-}".format(520,250)
'+520 250'
>>> "{:+} {:-}".format(520,-250)
'+520 -250'

#对千位数值进行分割
>>> "{:,}".format(1234)
'1,234'

>>> "{:.2f}".format(3.1415)
'3.14'
>>> "{:.2g}".format(3.1415)
'3.1'
>>> "{:.2g}".format(31415)
'3.1e+04'
>>> "{:.4g}".format(31415)
'3.142e+04'
>>> "{:.6}".format("I love curry")
'I love'

>>> "{:b}".format(123)
'1111011'
>>> "{:c}".format(123)
'{'
>>> "{:d}".format(123)
'123'
>>> "{:o}".format(123)
'173'
>>> "{:x}".format(123)
'7b'

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mrzsUCsa-1688700815140)(小甲鱼新版Python篇.assets/image-20230115134338878.png)]

9.F_字符串

​ f_string方法,只适用于python3.6以上版本,如果是python3.6一下版本可以使用format方法

>>> f"这是那年:{
      
      year}"
'这是那年:2010'
>>> f"1+1={
      
      1+1}"
'1+1=2'
>>> f"{
      
      -520:010}"
'-000000520'
>>> f"{
      
      123456:,}"
'123,456'

7.序列

​ 序列可以被分为两类:

​ 可变序列:列表

​ 不可变序列:元组,字符串

1.可以使用的运算符

>>> "123"*3
'123123123'
>>> [1,2,3]*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> (1,2,3)*3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> "123"+"456"
'123456'
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> (1,2,3)+(4,5,6)
(1, 2, 3, 4, 5, 6)

2.判断运算符

​ is:判断两个元素是否相同

​ not is:判断两个元素是否不相同

​ id:查看此元素的唯一值

>>> "curry" is "curry"
True
>>> (1,2,3) is (1,2,3)
True
>>> A = [1,2,3]
>>> B = [1,2,3]
>>> A is B
False
>>> id (A)
1880349856000
>>> id (B)
1880318812992

​ in:判断这个元素是否在当前列表中

​ not in :判断此元素是否不在当列表中

>>> A = "Curry"
>>> 'c' in A
False
>>> 'C' in A
True
>>> 'A'  not in A
True

3.清除序列

del:把当前的变量删除,不可以被调用

claer():清空当前变量中的内容

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

>>> A = [1,2,3]
>>> A.clear()
>>> A
[]

​ 切片删除:

>>> A = [1,2,3,4,5]
>>> del A[1:3]
>>> A
[1, 4, 5]
>>> A = [1,2,3,4,5]
>>> A[1:3]=[]
>>> A
[1, 4, 5]

4.跟序列有关的函数

​ 1.列表,元组和字符串互相转换

>>> list("Curry")
['C', 'u', 'r', 'r', 'y']
>>> list((1,2,3,4,5))
[1, 2, 3, 4, 5]
>>> tuple("curry")
('c', 'u', 'r', 'r', 'y')
>>> tuple([1,2,3,4,5])
(1, 2, 3, 4, 5)
>>> str([1,2,3,4,5])
'[1, 2, 3, 4, 5]'
>>> str((1,2,3,4,5))
'(1, 2, 3, 4, 5)'

​ mix():最小值

​ max():最大值

​ sum():总和

​ len():长度

>>> A=[1,2,3,4,5]
>>> min(A)
1
>>> max(A)
5
>>> A=[]
>>> max(A)
Traceback (most recent call last):
  File "<pyshell#109>", line 1, in <module>
    max(A)
ValueError: max() arg is an empty sequence
>>> max(A,default="空")
'空'

>>> A=[1,2,3,4,5]
>>> len(A)
5
>>> sum(A)
15
>>> sum(A,start=1)

​ sorted:排序

​ 格式:sort(变量名,key=排序类型)

​ reversed:反向迭代排序

>>> s = [1,3,5,6,10,9]
>>> sorted(s)
[1, 3, 5, 6, 9, 10]
>>> sorted(s,reverse=True)
[10, 9, 6, 5, 3, 1]
>>> A = ['A1','B22','C333',"D444"]
>>> sorted(A,key=len,reverse=True)
['C333', 'D444', 'B22', 'A1']


>>> reversed("Curry")
<reversed object at 0x000001B5CD981730>
>>> list(reversed("Curry"))
['y', 'r', 'r', 'u', 'C']
>>> list(reversed(range(0,10)))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

​ all:是否所有元素都为真

​ any:是否存在true元素

​ zip:可以将多个列表中的元素进行拼接然后变成元组,以最小长度的列表为单位

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> zip(a,b)
<zip object at 0x000001B5CD9393C0>
>>> list(zip(a,b))
[(1, 4), (2, 5), (3, 6)]
>>> c = 'curry'
>>> list(zip(a,b,c))
[(1, 4, 'c'), (2, 5, 'u'), (3, 6, 'r')]

​ itertools.zip_longest:以长度最长的为准

>>> import itertools
>>> zipped = itertools.zip_longest(a,b,c)
>>> list(zipped)
[(1, 4, 'c'), (2, 5, 'u'), (3, 6, 'r'), (None, None, 'r'), (None, None, 'y')]

​ map:根据函数类型,进行对列表计算

​ filter:根据函数类型对列表进行过滤,返回为true的元素

>>> list(map(pow,a,b))
[1, 32, 729]
>>> list(filter(str.islower,'Curry'))
['u', 'r', 'r', 'y']
>>> 

5.迭代参数与迭代器

​ 迭代参数可以被无限使用

​ 迭代器只有可以使用一次

​ iter:将列表转换为迭代器方式来进行存储

​ next:将迭代器中的数值提出

>>> x = [1,2,3,4,5]
>>> y = iter(x)
>>> type (x)
<class 'list'>
>>> type (y)
<class 'list_iterator'>
>>> next(y)
1
>>> next(y)
2
>>> next(y)
3
>>> next(y)
4
>>> next(y)
5
>>> next(y)
Traceback (most recent call last):
  File "<pyshell#171>", line 1, in <module>
    next(y)
StopIteration
>>> y = iter(x)
>>> next(y,"kong")
1
>>> next(y,"kong")
2
>>> next(y,"kong")
3
>>> next(y,"kong")
4
>>> next(y,"kong")
5
>>> next(y,"kong")
'kong'

8.字典

​ 字典是python中唯一实现映射关系的内置类型

​ 在列表中,元素是可以重复的,但是在字典中值是唯一的,不会出现重复的值

​ 字典的方法也是特别的多,但是一般和列表通用

1.创建字典

>>> a = {
    
    "库里":"Curry","233":"244"}
>>> b = dict({
    
    "库里":"Curry","233":"244"}
)
>>> c = dict(库里='curry',二三三='244')
>>> d = dict(zip(["库里","233"],["curry","244"]))

2.增加

​ dict.fromkeys:添加多个键,并可以指定默认值

​ 如果对已经创建好的字典进行添加的话,就可以直接指定一个不存在的值进行赋值,就是添加,如果存在了就是需改当前值

>>> d = dict.fromkeys("Curry",'none')
>>> d
{
    
    'C': 'none', 'u': 'none', 'r': 'none', 'y': 'none'}

>>> a['C']='c'
>>> a
{
    
    'A': 'a', 'B': 'c', 'C': 'c'}

3.删除

​ .pop:指定键删除

​ .popitem:在3.7之前的是随机删除,之后的时候删除最后一个添加的内容

>>> d = dict.fromkeys("Curry",'none')
>>> d
{
    
    'C': 'none', 'u': 'none', 'r': 'none', 'y': 'none'}

>>> d.pop('C')
'none'

>>> d.popitem()
('y', 'none')

键删除
>>> a
{
    
    '库里': 'Curry', '233': '244'}
>>> del a['233']
>>> a
{
    
    '库里': 'Curry'}

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

清空
>>> d
{
    
    'u': 'none', 'r': 'none'}
>>> d.clear()
>>> d
{
    
    }

4.改

​ .update:可以选择多个键进行改值

>>> a = {
    
    'A':'a','B':'b'}
>>> a['B']='c'
>>> a
{
    
    'A': 'a', 'B': 'c'}

>>> d = dict.fromkeys("curry")
>>> d
{
    
    'c': None, 'u': None, 'r': None, 'y': None}
>>> d['c']='C'
>>> d
{
    
    'c': 'C', 'u': None, 'r': None, 'y': None}
>>> d.update({
    
    'u':'U','r':'R'})
>>> d
{
    
    'c': 'C', 'u': 'U', 'r': 'R', 'y': None}

5.查

​ get:如果查的键不存在,可以使用第二个参数进行返回,以免报错

​ setdefault:如果查询的键不存在,就自动添加这个键,并赋予值

>>> d
{
    
    'c': 'C', 'u': 'U', 'r': 'R', 'y': None}
>>> d['c']
'C'
>>> d.get('C',"NO")
'NO'
>>> d.get('u')
'U'
>>> d.setdefault('k','K')
'K'
>>> d.setdefault('c','W')
'C'
>>> d
{
    
    'c': 'C', 'u': 'U', 'r': 'R', 'y': None, 'k': 'K'}

6.嵌套字典

>>> d = {
    
    "A":{
    
    'a':'1',"A":'一'}}
>>> d['A']['a']
'1'

列表嵌套字典 要通过位置变量进行提取
>>> d = {
    
    'A':['1','2','3'],'B':['1','2','3']}
>>> d['A'][0]
'1'

7.字段推导式

将键与值颠倒
>>> c = {i:j for j,i in d.items()}
>>> c
{'C': 'c', 'U': 'u', 'R': 'r', None: 'y', 'K': 'k'}

>>> c = {i:j for j,i in d.items() if i == 'C'}
>>> c
{'C': 'c'}

8.字典视图

如果源字典被改动,视图的所有值都会被更新,他们是实时关联的

​ keys():代表的是字典的键

​ values():代表的是字典的值

​ items():表示键与值

>>> d =dict.fromkeys("Curry","1")
>>> d
{
    
    'C': '1', 'u': '1', 'r': '1', 'y': '1'}
>>> keys=d.keys()
>>> values=d.values()
>>> items=d.items()
>>> keys
dict_keys(['C', 'u', 'r', 'y'])
>>> values
dict_values(['1', '1', '1', '1'])
>>> items
dict_items([('C', '1'), ('u', '1'), ('r', '1'), ('y', '1')])

9.集合

集合特性:

​ 1.集合具有唯一性

​ 2.集合是无序的

>>> type({
    
    })
<class 'dict'>
>>> type({
    
    ""})
<class 'set'>

集合推导式
>>> {
    
    i for i in "Curry"}
{
    
    'r', 'C', 'y', 'u'}

集合去重
>>> set([1,2,2,3,4,45,6,1])
{
    
    1, 2, 3, 4, 6, 45}
1.集合的方法

​ 1.copy():浅拷贝方法

>>> s = set("Curry")
>>> t = s.copy()
>>> t
{
    
    'r', 'C', 'y', 'u'}
>>> s.pop()
'r'
>>> s
{
    
    'C', 'y', 'u'}
>>> t
{
    
    'r', 'C', 'y', 'u'}

​ 2.isdisjoint():对比这两个集合是否有内容相关

>>> s = set("PHP")
>>> s.isdisjoint(set("Python"))
False
>>> s.isdisjoint(set("JAVA"))
True

​ 3.issubset():查看是否是这个集合的子集

​ 子集:对于两个集合A B,如果A中任意一个元素是集合B中的元素,称集合A为集合B的子集

>>> s.issubset("Python")
False
>>> s.issubset("PHP-Py")
True

​ 4.issuperset():查看这个集合是否为对比集合的超集

​ 超集:与子集相反,如果在B对象中任意一个元素为集合A中的元素,就称为B为A的超集

>>> s.issuperset("PHP_py")
False
>>> s.issuperset("PHP")
True
>>> s.issuperset("PH")
True

​ 5.union():将两个元素合并为一个元素

​ 并集:对于两个集合,把他们的元素合并在一起

>>> s.union({1,2,3,4})
{1, 2, 3, 'P', 4, 'H'}

​ 6.intersection():

​ 交集:这两个元素的相同元素

>>> s.intersection("Python")
{
    
    'P'}

​ 7.difference():

​ 差集:这两个元素的不同元素

>>> s.difference("Python")
{
    
    'H'}
2.集合的增删改查
1.增
>>> s = set("Curry")
>>> s
{
    
    'r', 'C', 'y', 'u'}
>>> s.update([1,2],"23")
>>> s
{
    
    1, 2, 'u', '2', 'C', 'y', '3', 'r'}

>>> s
{
    
    1, 2, 'u', '2', 'C', 'y', '3', 'r'}
>>> s.add("233")
>>> s
{
    
    1, 2, '233', 'u', '2', 'C', 'y', '3', 'r'}

​ 注意:在创建集合时一个字符串是按照多个字符去创建的,但是使用add方法是把字符串当作一个整体安装的

​ 刚刚上面举例的交集和差集可以配合update使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nuRk619b-1688700815141)(小甲鱼新版Python篇.assets/image-20230120124351867.png)]

2.删

​ remove:如果删除不存在的值,会报错

​ discard:静默删除,不存在也不会报错

​ pop:随机删除,从一个开始

​ clear:清空集合

>>> s
{
    
    1, 2, '233', 'u', '2', 'C', 'y', '3', 'r'}
>>> s.remove("233")
>>> s
{
    
    1, 2, 'u', '2', 'C', 'y', '3', 'r'}
>>> s.remove("244")
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    s.remove("244")
KeyError: '244'
>>> s.discard("244")
>>> s.pop(1)
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    s.pop(1)
TypeError: pop() takes no arguments (1 given)
>>> s.pop()
1
>>> s.pop()
2

>>> s.clear()
>>> s
set()
3.第二种集合类型

​ set():集合:可变

​ frozenset():集合:不可变

>>> a = frozenset("Curry")
>>> a
frozenset({
    
    'r', 'C', 'y', 'u'})
4.可哈希

​ 可哈希:如果这个值不会在被改变,比如字符串,元组

​ 不可哈希:这个值可以做出改变,比如列表,字典

在哈希中,整数返回的肯定是本身自己,其他说的是随机生成的

>>> hash(1)
1
>>> hash(1.0)
1
>>> hash(3.1415)
326276785803738115

>>> hash("A")
-9056477081050699732
>>> hash([1,2,3])
Traceback (most recent call last):
  File "<pyshell#97>", line 1, in <module>
    hash([1,2,3])
TypeError: unhashable type: 'list'
>>> hash({
    
    'A':'a','B':'b'})
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    hash({
    
    'A':'a','B':'b'})
TypeError: unhashable type: 'dict'
>>> hash({
    
    1,2,3,4})
Traceback (most recent call last):
  File "<pyshell#99>", line 1, in <module>
    hash({
    
    1,2,3,4})
TypeError: unhashable type: 'set'
>>> a = frozenset('abc')
>>> a
frozenset({
    
    'c', 'b', 'a'})
>>> hash(a)
3392920615793529278

猜你喜欢

转载自blog.csdn.net/weixin_53678904/article/details/131593576