python基本数据结构

列表list

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

Python有6个序列的内置类型,但最常见的是列表和元组,包括前面所介绍的字符串。字符串是字符的序列,列表和元组则是任意python数据类型或对象的序列。

序列都可以进行的操作包括索引,切片,加,乘,检查成员。

此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。

列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。

列表的数据项不需要具有相同的类型

list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5 ];
list3 = ["a", "b", "c", "d"];
list4 = list()
print(list4)
[]

访问列表中的值

与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。

list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
 
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
list1[0]:  Google
list2[1:5]:  [2, 3, 4, 5]

更新列表

你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示

list1 = ['Google', 'Runoob', 1997, 2000]
 
print ("第三个元素为 : ", list1[2])
list1[2] = 2001
print ("更新后的第三个元素为 : ", list1[2])
第三个元素为 :  1997
更新后的第三个元素为 :  2001
a  =[1,2,3]
print(a,id(a))
b = a #赋值引用,a 和 b 都指向同一个对象
a[1] =555
print(b,id(b))

a  =[1,2,3]
print(a,id(a))
b = a[:]
a[1] =555
print(b,id(b))


a  =[1,2,3]
print(a,id(a))
b = a
a = [1,2]
print(a,id(a))
print(b,id(b))
[1, 2, 3] 139941048300424
[1, 555, 3] 139941048300424
[1, 2, 3] 139941047707400
[1, 2, 3] 139941048237448
[1, 2, 3] 139941048235336
[1, 2] 139941048300424
[1, 2, 3] 139941048235336

删除列表元素

可以使用 del 语句来删除列表的的元素,如下实例:

list1 = ['Google', 'Runoob', 1997, 2000]
 
print ("原始列表 : ", list)
del list1[2]
print ("删除第三个元素 : ", list1)
原始列表 :  ['Google', 'Runoob', 1997, 2000]
删除第三个元素 :  ['Google', 'Runoob', 2000]

列表脚本操作符

列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

Python 表达式结果描述
len([1, 2, 3])3长度
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]组合
[‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]重复
3 in [1, 2, 3]True元素是否存在于列表中
for x in [1, 2, 3]: print(x, end=" ")1 2 3迭代
squares = [1, 4, 9, 16, 25]
squares += [36, 49, 64, 81, 100]
squares

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
len([1, 2, 3]) 	
3
['Hi!'] * 4 
['Hi!', 'Hi!', 'Hi!', 'Hi!']
for x in [1, 2, 3]: print(x, end=" ") 
1 2 3 

列表截取与拼接

Python的列表截取与字符串操作类型,如下所示:

alist = [0,1,2,3,4,5,6,7]

操作:

Python 表达式结果描述
alist[2]2读取第三个元素
alist[-2]6从右侧开始读取倒数第二个元素: count from the right
alist[1:][1, 2, 3, 4, 5, 6, 7]输出从第二个元素开始后的所有元素
alist[::-1][7, 6, 5, 4, 3, 2, 1, 0]从右到左取全部成员
alist[::2][0, 2, 4, 6]每隔1取一个成员
alist[5:0:-2][5, 3, 1]从5至0(不包括0)从右至左每隔一个成员取一个成员
alist = [0,1,2,3,4,5,6,7]
print(alist[2])
print(alist[-2])
print(alist[1:])

print(alist[::-1])#从右到左取全部成员
print(alist[::2])      #每隔1取一个成员
print(alist[0:5:2])   #从0至4每隔一个取一项
print(alist[5:0:-2])   #从5至0(不包括0)从右至左每隔一个成员取一个成员
2
6
[1, 2, 3, 4, 5, 6, 7]
[7, 6, 5, 4, 3, 2, 1, 0]
[0, 2, 4, 6]
[0, 2, 4]
[5, 3, 1]

嵌套列表

a = ['a', 'b', 'c']
n = [1, 2, 3]
x = [a, n]
print(x)
print(x[0])
print(x[0][1])
[['a', 'b', 'c'], [1, 2, 3]]
['a', 'b', 'c']
b
  • 直接赋值:其实就是对象的引用(别名)。
  • 浅拷贝(copy):拷贝父对象,不会拷贝对象的内部的子对象。
  • 深拷贝(deepcopy): copy 模块的 deepcopy 方法,完全拷贝了父对象及其子对象。

b = a: 赋值引用,a 和 b 都指向同一个对象

b = a.copy(): 浅拷贝, a 和 b 是一个独立的对象,但他们的子对象还是指向统一对象(是引用)

b = copy.deepcopy(a): 深度拷贝, a 和 b 完全拷贝了父对象及其子对象,两者是完全独立的

直接赋值

names = ["4ZhangYang", "#!Guyun","xXiangPeng",["alex","jack"],"ChenRonghua","XuLiangchen"]
name2 = names
print(names,id(names))
print(name2,id(name2))
names[2] = "向鹏"
names[3][0] ="ALEXANDER"
print(names,id(names))
print(name2,id(name2))
name2[3][0] ="ALEX"
print(names,id(names))
print(name2,id(name2))

['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629997780296
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629997780296
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629997780296
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629997780296
['4ZhangYang', '#!Guyun', '向鹏', ['ALEX', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629997780296
['4ZhangYang', '#!Guyun', '向鹏', ['ALEX', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629997780296

浅拷贝

只拷贝第一层,拷贝地是子列表的内存地址


names = ["4ZhangYang", "#!Guyun","xXiangPeng",["alex","jack"],"ChenRonghua","XuLiangchen"]
name2 = names.copy()
print(names,id(names))
print(name2,id(name2))


names[2] = "向鹏"
names[3][0] ="ALEXANDER"
print(names,id(names))
print(name2,id(name2))
name2[3][0] ="ALEX"
print(names,id(names))
print(name2,id(name2))

['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998662280
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998080968
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998662280
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['ALEXANDER', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998080968
['4ZhangYang', '#!Guyun', '向鹏', ['ALEX', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998662280
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['ALEX', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998080968

深拷贝

import copy

names = ["4ZhangYang", "#!Guyun","xXiangPeng",["alex","jack"],"ChenRonghua","XuLiangchen"]
name2 = copy.deepcopy(names)
print(names,id(names))
print(name2,id(name2))

names[2] = "向鹏"
names[3][0] ="ALEXANDER"
print(names,id(names))
print(name2,id(name2))
name2[3][0] ="ALEX"
print(names,id(names))
print(name2,id(name2))

['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998080968
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139630060941768
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998080968
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['alex', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139630060941768
['4ZhangYang', '#!Guyun', '向鹏', ['ALEXANDER', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139629998080968
['4ZhangYang', '#!Guyun', 'xXiangPeng', ['ALEX', 'jack'], 'ChenRonghua', 'XuLiangchen'] 139630060941768

列表函数&方法

列表函数

序号函数解释
1len(list)列表元素个数
2max(list)返回列表元素最大值
3min(list)返回列表元素最小值
4list(seq)将元组转换为列表
5sorted(list)列表排序
6zip(list1,list2)将列表元素逐一配对
7all(list)list中所有项为真,则返回真,否则返回假
8any(list)list中有一项为真,则返回真,否则返回假
9enumerate(list)将可迭代对象的每一个元素与其对应的索引值组成一个元组并返回

sorted(iterable, cmp=None, key=None, reverse=False)

  • iterable:是可迭代类型;
  • cmp:用于比较的函数,比较什么由key决定;
  • key:用列表元素的某个属性或函数进行作为关键字,有默认值,迭代集合中的一项;
  • reverse:排序规则. reverse = True 降序 或者 reverse = False 升序,有默认值。
sorted([36,6,-12,9,-22])  
[-22, -12, 6, 9, 36]
sorted([36,6,-12,9,-22],key=abs) #高阶函数,以绝对值大小排序
[6, 9, -12, -22, 36]
a = [('b',2), ('a',1), ('c',0)]
list(sorted(a,key=lambda x:x[1]))   #按照元组第二个元素排序
[('c', 0), ('a', 1), ('b', 2)]
list(sorted(a,key=lambda x:x[0]))   #按照元组第一个元素排序
[('a', 1), ('b', 2), ('c', 0)]
sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower) #忽略大小写排序
['about', 'bob', 'Credit', 'Zoo']
sorted(['bob', 'about', 'Zoo', 'Credit'],key=str.lower,reverse=True) #反向排序
['Zoo', 'Credit', 'bob', 'about']
from operator import itemgetter, attrgetter 
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]  
print(sorted(students, key=itemgetter(0)) )
sorted(students, key=itemgetter(1,2))  
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]





[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

zip

list_1 = [1,2,3]
list_2 = ['a','b','c']
tuple1 = ('sun','cheng','quan')
s = zip(list_1,list_2)
a = list(s)
print(a)
print(list(zip(*a)))

list(zip(list_1,list_2,tuple1))
[(1, 'a'), (2, 'b'), (3, 'c')]
[(1, 2, 3), ('a', 'b', 'c')]





[(1, 'a', 'sun'), (2, 'b', 'cheng'), (3, 'c', 'quan')]

len

list1 = [ 'Runoob', 'Taobao','Google']
print (len(list1))

c = (i for i in range(5))
print(type(c))
list2 = list(range(5)) 
print (type(list2),len(list2))

3
<class 'generator'>
<class 'list'> 5

all /any

alist = [0,1,2,3]
print(all(alist) )
print(any(alist) )
False
True

enumerate

list1 = [4,2,6,56,9]
print(enumerate(list1))
print(list(enumerate(list1)))
<enumerate object at 0x7efe246bac60>
[(0, 4), (1, 2), (2, 6), (3, 56), (4, 9)]

列表方法

序号方法解释
1list.append(obj)在列表末尾添加新的对象
2list.count(obj)统计某个元素在列表中出现的次数
3list.extend(seq)在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4list.index(obj)从列表中找出某个值第一个匹配项的索引位置
5list.insert(index, obj)将对象插入列表
6list.pop([index=-1])移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7list.remove(obj)移除列表中某个值的第一个匹配项
8list.reverse()反向列表中元素
9list.sort(cmp=None, key=None, reverse=False)对原列表进行排序
10list.clear()清空列表
11list.copy()复制列表
alist = [1,2,3,4,5]     #建立一个列表
alist.append(1)         #列表尾部追加元素1
alist
[1, 2, 3, 4, 5, 1]
alist.count(1)          #统计1在列表中出现次数
2
alist.extend([2,'chengquan'])  #列表后追加另一个列表所有元素
alist
[1, 2, 3, 4, 5, 1, 2, 'chengquan']
alist.index(2)                  #元素2在列表中首先出现序号
1
alist.insert(3,'sun')           #在序号3处插入元素‘sun’
alist
[1, 2, 3, 'sun', 4, 5, 1, 2, 'chengquan']
alist.pop()                      #返回并删除列表最后一个元素
'chengquan'
alist
[1, 2, 3, 'sun', 4, 5, 1, 2]
alist.remove(1)                   #删除列表中的元素1(仅删除第一个)
alist

[2, 3, 'sun', 4, 5, 1, 2]
alist.reverse()                   #列表内元素顺序颠倒
alist
[2, 1, 5, 4, 'sun', 3, 2]

列表推导式

multiples = [i for i in range(30) if i % 3 is 0]
print(multiples)
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

元组tuple

元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple

元组创建

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

tup1 = ('Google', 'Runoob', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";   #  不需要括号也可以

print(type(tup3))
print(tup3)

2,3 #直接用逗号隔开的两个值,可以创建一个元组
<class 'tuple'>
('a', 'b', 'c', 'd')





(2, 3)

创建空元组

tup1 = ()
tup1
()

元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用

tup1 = (50)
print(type(tup1))    # 不加逗号,类型为整型

 
tup1 = (50,)
print(type(tup1))    # 加上逗号,类型为元组
<class 'int'>
<class 'tuple'>
x,y = 2,3
print(x,y)
x,y=y,x #交换x与y的值(本质上右边是一个元组)
y,x 
x,y
2 3





(3, 2)

访问元组

元组可以使用下标索引来访问元组中的值,如下实例:

up1 = ('Google', 'Runoob', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
 
print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])
tup1[0]:  50
tup2[1:5]:  (2, 3, 4, 5)

修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')
 
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
 
# 创建一个新的元组
tup3 = tup1 + tup2;
print (tup3)
(12, 34.56, 'abc', 'xyz')

删除元组

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup;
print ("删除后的元组 tup : ")
print (tup)
('Google', 'Runoob', 1997, 2000)
删除后的元组 tup : 



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-31-cc087dd11595> in <module>
      4 del tup;
      5 print ("删除后的元组 tup : ")
----> 6 print (tup)


NameError: name 'tup' is not defined

元组运算符

与字符串一样,元组之间可以使用 + 号和 * 号进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组

Python 表达式结果描述
len((1, 2, 3))3计算元素个数
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)连接
(‘Hi!’,) * 4(‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’)复制
3 in (1, 2, 3)True元素是否存在
for x in (1, 2, 3): print (x,)1 2 3迭代

元组索引,截取

Python 表达式结果描述
L[2]‘Runoob’读取第三个元素
L[-2]‘Taobao’反向读取;读取倒数第二个元素
L[1:](‘Taobao’, ‘Runoob’)截取元素,从第二个开始后的所有元素

元组内置函数

len(tuple)

计算元组元素个数

tuple1 = ('Google', 'Runoob', 'Taobao')
len(tuple1)
3

max(tuple)

返回元组中元素最大值

tuple2 = ('5', '4', '8')
max(tuple2)
'8'

min(tuple)

返回元组中元素最小值

tuple2 = ('5', '4', '8')
min(tuple2)
'4'

tuple(seq)

将列表转换为元组

list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
tuple1=tuple(list1)
tuple1
('Google', 'Taobao', 'Runoob', 'Baidu')

字典(dictionary)

dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度

为什么dict查找速度这么快?因为dict的实现原理和查字典是一样的。假设字典包含了1万个汉字,我们要查某一个字,一个办法是把字典从第一页往后翻,直到找到我们想要的字为止,这种方法就是在list中查找元素的方法,list越大,查找越慢。

第二种方法是先在字典的索引表里(比如部首表)查这个字对应的页码,然后直接翻到该页,找到这个字。无论找哪个字,这种查找速度都非常快,不会随着字典大小的增加而变慢。

和list比较,dict有以下几个特点:

  • 查找和插入的速度极快,不会随着key的增加而变慢;
  • 需要占用大量的内存,内存浪费多。

而list相反:

  • 查找和插入的时间随着元素的增加而增加;
  • 占用空间小,浪费内存很少。

所以,dict是用空间来换取时间的一种方法。

创建

{}            #建立空字典
{}
dict()        #建立空字典
{}
adict = {'a':1, 'b':2, 'c':'sunchengquan'}
adict['c']    #用键名引用成员
'sunchengquan'

访问字典里的值

adict = {'a':'sun','b':'cheng','c':'quan'}
print ("adict['a']: ", adict['a'])
print ("adict['b']: ", adict['b'])
adict['a']:  sun
adict['b']:  cheng

修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例

adict = {'a':'sun','b':'cheng','c':'quan','age':27}

adict['age'] = 28;               # 更新 Age
adict['school'] = "lzu"  # 添加信息
 
print ("adict['Age']: ", adict['age'])
print ("adict['School']: ", adict['school'])
adict['Age']:  28
adict['School']:  lzu

删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。

显示删除一个字典用del命令,如下实例:

adict = {'a':'sun','b':'cheng','c':'quan','age':27,'school':"lzu" }

del adict['a'] # 删除键 'Name'
# adict.clear()     # 清空字典
# del adict         # 删除字典

print ("adict['age']: ", adict['age'])
print ("adict['school']: ", adict['school'])
adict['age']:  27
adict['school']:  lzu

字典键的特性

1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例

adict = {'a':'sun','b':'cheng','c':'quan','age':27,'school':"lzu" ,'age':28}
print ("adict['age']: ", adict['age'])
adict['age']:  28

2)键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行,如下实例:

adict = {['a']:'sun','b':'cheng','c':'quan','age':27,'school':"lzu" ,'age':28}
adict
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-58-e4143dbffaef> in <module>
----> 1 adict = {['a']:'sun','b':'cheng','c':'quan','age':27,'school':"lzu" ,'age':28}
      2 adict


TypeError: unhashable type: 'list'
adict = {('a',):'sun','b':'cheng','c':'quan','age':27,'school':"lzu" ,'age':28}
adict
{('a',): 'sun', 'b': 'cheng', 'c': 'quan', 'age': 28, 'school': 'lzu'}

字典内置函数&方法

字典内置函数

len(dict)计算字典元素个数,即键的总数

adict = {('a',):'sun','b':'cheng','c':'quan','age':27,'school':"lzu" ,'age':28}
len(adict)
5

str(dict)输出字典,以可打印的字符串表示

str(adict)
"{('a',): 'sun', 'b': 'cheng', 'c': 'quan', 'age': 28, 'school': 'lzu'}"

type(variable)返回输入的变量类型,如果变量是字典就返回字典类型

type(adict)
dict

字典内置方法

序号函数描述
1dict.clear()删除字典内所有元素
2dict.copy()返回一个字典的浅复制
3dict.fromkeys()创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4dict.get(key, default=None)返回指定键的值,如果值不在字典中返回default值
5key in dict如果键在字典dict里返回true,否则返回false
6dict.items()以列表返回可遍历的(键, 值) 元组数组
7dict.keys()返回一个迭代器,可以使用 list() 来转换为列表
8dict.setdefault(key, default=None)和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9dict.update(dict2)把字典dict2的键/值对更新到dict里
10dict.values()返回一个迭代器,可以使用 list() 来转换为列表
11pop(key[,default])删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值
12popitem()随机返回并删除字典中的一对键和值(一般删除末尾对)
dict.clear()
adict = {'a':'sun','b':'cheng','c':'quan','age':27,'school':"lzu" }
print ("字典长度 : %d" %  len(adict))
adict.clear()
print ("字典删除后长度 : %d" %  len(adict))
字典长度 : 5
字典删除后长度 : 0
dict.copy()
dict1 = {'Name': 'Sun', 'Age': 7, 'Class': 'First'}
 
dict2 = dict1.copy()
print ("新复制的字典为 : ",dict2)
新复制的字典为 :  {'Name': 'Sun', 'Age': 7, 'Class': 'First'}

直接赋值、浅拷贝和深度拷贝解析

import copy
dict1 =  {'user':'runoob','num':[1,2,3]}
 
dict2 = dict1          # 浅拷贝: 引用对象
dict3 = dict1.copy()   # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dict4 = copy.deepcopy(dict1) #深拷贝


# 修改 data 数据
dict1['user']='root'
dict1['num'].remove(1)
 
# 输出结果
print(dict1)
print(dict2)
print(dict3)
print(dict4)


{'user': 'root', 'num': [2, 3]}
{'user': 'root', 'num': [2, 3]}
{'user': 'runoob', 'num': [2, 3]}
{'user': 'runoob', 'num': [1, 2, 3]}
dict.fromkeys()
seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print ("新的字典为 : %s" %  str(dict))

dict = dict.fromkeys(seq, 10)
print ("新的字典为 : %s" %  str(dict))
新的字典为 : {'name': None, 'age': None, 'sex': None}
新的字典为 : {'name': 10, 'age': 10, 'sex': 10}
dict.get(key, default=None)
adict = {'a':'sun','b':'cheng','c':'quan'} 
print(adict.get('a'))                            #获取键‘a’对应的值
print(adict.get('d')) 
print(adict.get('d',0)) 
sun
None
0
adict['d']                   #直接获取值,不存在而发生错误 
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-82-9fd784d666f4> in <module>
----> 1 adict['d']                   #直接获取值,不存在而发生错误


KeyError: 'd'
key in dict
dict = {'Name': 'Sun', 'Age': 7}
 
# 检测键 Age 是否存在
if  'Age' in dict:
    print("键 Age 存在")
else :
    print("键 Age 不存在")

# 检测键 Sex 是否存在
if  'Sex' in dict:
    print("键 Sex 存在")
else :
    print("键 Sex 不存在")
 
 
# not in
 
# 检测键 Age 是否存在
if  'Age' not in dict:
    print("键 Age 不存在")
else :
    print("键 Age 存在")
键 Age 存在
键 Sex 不存在
键 Age 存在
dict.items()
adict = {'a':'sun','b':'cheng','c':'quan'} 
print ("Value : %s" %  dict.items())
Value : dict_items([('Name', 'Sun'), ('Age', 7)])
dict.keys()
print(adict.keys())
print(list(adict.keys() ))
dict_keys(['a', 'b', 'c'])
['a', 'b', 'c']
dict.setdefault(key, default=None)
adict.setdefault('a')       #若字典存在键‘a’,则返回其对应的值
'sun'
adict.setdefault('d','sunchengquan')#不存在,则在字典中建立一个键值对
'sunchengquan'
adict
{'a': 'sun', 'b': 'cheng', 'c': 'quan', 'd': 'sunchengquan'}
dict.update(dict)
adict.update({"c":"QUAN"})
print(adict)
adict.update({"e":"wow!!!"})
print(adict)
{'a': 'sun', 'b': 'cheng', 'c': 'QUAN', 'd': 'sunchengquan'}
{'a': 'sun', 'b': 'cheng', 'c': 'QUAN', 'd': 'sunchengquan', 'e': 'wow!!!'}
dict.values()
print ("字典所有值为 : ",  list(adict.values()))
字典所有值为 :  ['sun', 'cheng', 'QUAN', 'sunchengquan', 'wow!!!']
pop(key[,default])
print(adict.pop('d') )              #删除d键值对并返回值
print(adict)
sunchengquan
{'a': 'sun', 'b': 'cheng', 'c': 'QUAN', 'e': 'wow!!!'}
adict.pop('d')               #删除不存在的键值对,发生错误
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-97-96ffccefb11b> in <module>
----> 1 adict.pop('d')               #删除不存在的键值对,发生错误


KeyError: 'd'
print(adict.pop("d","nokey"),adict); # 设置默认值,必须添加,否则报错
nokey {'a': 'sun', 'b': 'cheng', 'c': 'QUAN', 'e': 'wow!!!'}
popitem()

popitem() 方法随机返回并删除字典中的一对键和值(一般删除末尾对)。

如果字典已经为空,却调用了此方法,就报出KeyError异常。

print(adict.popitem())              #删除任一项键值对并返回
('e', 'wow!!!')
adict
{'a': 'sun', 'b': 'cheng', 'c': 'QUAN'}

字典推导式

mcase = {'a': 10, 'b': 34}
mcase_frequency = {v: k for k, v in mcase.items()}
print (mcase_frequency)
{10: 'a', 34: 'b'}

集合set

集合(set)是一个无序的不重复元素序列。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)                      # 这里演示的是去重功能

print('orange' in basket)                 # 快速判断元素是否在集合内

print('crabgrass' in basket)

 
# 下面展示两个集合间的运算.

a = set('abracadabra')
b = set('alacazam')
print(a )                                 

print(a - b )                             

print(a | b )                             # 集合a或b中包含的所有元素

print(a & b )                             # 集合a和b中都包含了的元素

print(a ^ b )                             # 不同时包含于a和b的元素

{'apple', 'banana', 'pear', 'orange'}
True
False
{'a', 'b', 'r', 'c', 'd'}
{'d', 'b', 'r'}
{'a', 'b', 'r', 'l', 'c', 'd', 'm', 'z'}
{'c', 'a'}
{'z', 'd', 'r', 'm', 'b', 'l'}

集合推导式

类似列表推导式,同样集合支持集合推导式(Set comprehension):

a = {x for x in 'abracadabra' if x not in 'abc'}
a
{'d', 'r'}

添加元素

  • add()
  • update()
thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)

{'Taobao', 'Runoob', 'Google', 'Facebook'}
thisset = set(("Google", "Runoob", "Taobao"))
thisset.update({1,3})
print(thisset)
thisset.update([1,4],[5,6])  
print(thisset)
{1, 'Runoob', 3, 'Taobao', 'Google'}
{1, 'Runoob', 3, 4, 5, 6, 'Taobao', 'Google'}

移除元素

  • remove()
  • discard()
  • pop()
thisset = set(("Google", "Runoob", "Taobao"))
thisset.remove("Taobao")
print(thisset)
thisset.remove("Facebook")   # 不存在会发生错误
{'Runoob', 'Google'}



---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-108-bece1975c10b> in <module>
      2 thisset.remove("Taobao")
      3 print(thisset)
----> 4 thisset.remove("Facebook")   # 不存在会发生错误


KeyError: 'Facebook'
thisset = set(("Google", "Runoob", "Taobao"))
thisset.discard("Facebook")  # 不存在不会发生错误
print(thisset)
{'Taobao', 'Runoob', 'Google'}

我们也可以设置随机删除集合中的一个元素

thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()
 
print(x)
print(thisset)
Taobao
{'Runoob', 'Google', 'Facebook'}

计算集合元素个数

thisset = set(("Google", "Runoob", "Taobao"))
len(thisset)
3

清空集合

thisset = set(("Google", "Runoob", "Taobao"))
thisset.clear()
print(thisset)
set()

判断元素是否在集合中存在

thisset = set(("Google", "Runoob", "Taobao"))
print("Runoob" in thisset)

print("Facebook" in thisset)

True
False

集合内置方法完整列表

方法描述
add()为集合添加元素
clear()移除集合中的所有元素
copy()拷贝一个集合
difference()返回多个集合的差集
difference_update()移除集合中的元素,该元素在指定的集合也存在
discard()删除集合中指定的元素
intersection()返回集合的交集
intersection_update()删除集合中的元素,该元素在指定的集合中不存在
isdisjoint()判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False
issubset()判断指定集合是否为该方法参数集合的子集
issuperset()判断该方法的参数集合是否为指定集合的子集
pop()随机移除元素
remove()移除指定元素
symmetric_difference()返回两个集合中不重复的元素集合
symmetric_difference_update()移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中
union()返回两个集合的并集
update()给集合添加元素

difference()


x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
 
z = x.difference(y) 
 
print(z)

{'banana', 'cherry'}

intersection()


x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
z = x.intersection(y) 
 
print(z)

{'apple'}

intersection_update()

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
x.intersection_update(y) 
 
print(x)
{'apple'}
x = {"a", "b", "c"}
y = {"c", "d", "e"}
z = {"f", "g", "c"}
 
x.intersection_update(y, z)
 
print(x)
{'c'}

isdisjoint()

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "facebook"}
 
z = x.isdisjoint(y) 
 
print(z)

True

issubset()

判断集合 x 的所有元素是否都包含在集合 y 中

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b", "a"}
 
z = x.issubset(y) 
 
print(z)

True

如果没有全部包含返回 False

x = {"a", "b", "c"}
y = {"f", "e", "d", "c", "b"}
 
z = x.issubset(y) 
 
print(z)

False

issuperset()

判断集合 y 的所有元素是否都包含在集合 x 中

x = {"f", "e", "d", "c", "b", "a"}
y = {"a", "b", "c"}
 
z = x.issuperset(y) 
 
print(z)

True

如果没有全部包含返回 False

x = {"f", "e", "d", "c", "b"}
y = {"a", "b", "c"}
 
z = x.issuperset(y) 
 
print(z)

False

symmetric_difference()

返回两个集合组成的新集合,但会移除两个集合的重复元素

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
z = x.symmetric_difference(y) 
 
print(z)

{'banana', 'runoob', 'cherry', 'google'}

symmetric_difference_update()

移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
x.symmetric_difference_update(y) 
 
print(x)

{'banana', 'runoob', 'cherry', 'google'}

union()

x = {"apple", "banana", "cherry"}
y = {"google", "runoob", "apple"}
 
z = x.union(y) 
 
print(z)

{'apple', 'banana', 'runoob', 'cherry', 'google'}

合并多个集合

x = {"a", "b", "c"}
y = {"f", "d", "a"}
z = {"c", "d", "e"}
 
result = x.union(y, z) 
 
print(result)

{'c', 'a', 'f', 'e', 'd', 'b'}

函数frozenset()

set1 = {'c', 'a', 'f', 'e', 'd', 'b'}
set2 = frozenset(set1)
print(set2)
set2.remove(2)
frozenset({'c', 'a', 'f', 'e', 'd', 'b'})



---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-130-1f096bd4e2ca> in <module>
      2 set2 = frozenset(set1)
      3 print(set2)
----> 4 set2.remove(2)


AttributeError: 'frozenset' object has no attribute 'remove'
  • 11
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值