基本数据类型(二)
元组(tup)
元组与列表相似,不同之处在于元组的元素不能修改。元组的创建,只需要在括号中添加元素,并使用逗号隔开,如:
>>> tup = ('Star','Male',23,'play game') >>> tup2 = 'a','b','c','d' # 不需要括号也行 >>> type(tup2) <class 'tuple'>
元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被仿作运算符使用,如:
>>> tup3 = ('aabb') # 不加括号,类型为字符串 >>> type(tup3) <class 'str'> >>> tup4 = ('aabb',) # 加上逗号,类型为元组 >>> type(tup4) <class 'tuple'>
访问元组
元组可以使用下标索引来访问元组中的值,如:
>>> tup = ('Star','Male',23,'play game') >>> print(tup[0]) Star >>> print(tup[0:2]) ('Star', 'Male')
修改元祖
元组中的元素值是不允许修改的,但我们可以将元组转换为列表,更改列表,然后再将列表转换回元组,如:
>>> tup = ('Star','Male',23,'play game') >>> list = list(tup) >>> list[1] = 'female' >>> tup = tuple(list) >>> print(tup) ('Star', 'female', 23, 'play game')
删除元组
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如:
>>> tup = ('Star','Male',23,'play game') >>> print(tup) ('Star', 'Male', 23, 'play game') >>> del tup >>> print(tup) # 元组被删除后,输出变量会有异常信息,因为元组已不存在 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'tup' is not defined
元组运算符
与字符串一样,元组之间可以使用'+'和'*'进行运算。这就意味着他们可以组合和复制,运算后会生成一个新的元组:
>>> len((1,2,3,45,66,77)) 6 >>> (1,2,3)+(45,66,77) (1, 2, 3, 45, 66, 77) >>> ('hi')*6 'hihihihihihi' >>> ('hi',)*6 ('hi', 'hi', 'hi', 'hi', 'hi', 'hi') >>> 3 in (1,2,3) True >>> for x in (1,2,3):print(x,) ... 1 2 3
元组内置函数
>>> tup = (11,56,789,2435,234542) >>> len(tup) # 计算元组元素个数 5 >>> max(tup) # 返回元组中元素最大值 234542 >>> min(tup) # 返回元组中元素最小值 11
集合(set)
集合是一个无序和无索引的不重复元素序列,用'{}'创建,如: s = {1,2,3,44,56,77}
创建一个空几个必须使用set()而不是'{}',因为'{}'是用来创建一个空字典:
>>> d = {} >>> type(d) <class 'dict'> >>> s = set() >>> type(s) <class 'set'>
下面展示两个集合间的运算:
>>> a = set('abcdefghijkl') >>> b = set('asdfjklqwetbnm') >>> a {'k', 'c', 'j', 'a', 'd', 'b', 'i', 'h', 'f', 'l', 'g', 'e'} >>> a - b # 集合a中包含而集合b中不包含的元素 {'g', 'c', 'i', 'h'} >>> a | b # 集合a或b都包含的所有元素 {'k', 'c', 'm', 'd', 'q', 'l', 's', 'g', 'e', 't', 'j', 'a', 'n', 'b', 'i', 'w', 'h', 'f'} >>> a & b # 集合a和b都包含了的元素 {'k', 'j', 'a', 'd', 'b', 'f', 'l', 'e'} >>> a ^ b # 不同时包含于a和b的元素 {'t', 'c', 'n', 'm', 'w', 'i', 'q', 'h', 's', 'g'}
集合的基本操作
添加元素
>>> s = {'youtube','twitter','instagram'}
>>> s.add('facebook') # add()方法将一个元素添加到集合
>>> print(s)
{'twitter', 'instagram', 'youtube', 'facebook'}
>>> s.update({1,2}) # update()方法向集合中添加多个元素,用','分开,且参数可以是列表,元祖,字典等
>>> print(s)
{'twitter', 1, 'instagram', 'youtube', 'facebook', 2}
>>> s.update([1,3],[2,4])
>>> print(s)
{'twitter', 1, 'instagram', 'youtube', 'facebook', 2, 3, 4}
删除元素
>>> s = {'youtube','twitter','instagram','facebook'}
>>> s.remove('facebook') # remove()将元素从集合中移除,如果元素不存在,则会发送错误
>>> print(s)
{'twitter', 'instagram', 'youtube'}
>>> s.remove('facebook')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'facebook'
>>> s.discard('facebook') # discard()方法也是移除集合中的元素,但如果元素不存在,不会发生错误
>>> s
{'twitter', 'instagram', 'youtube'}
>>> s.pop() # pop()方法随机删除集合中的一个元素
'twitter'
>>> s
{'instagram', 'youtube'}
>>> s.clear() # clear()方法则是清空集合
>>> s
set()
>>> del s # del是彻底删除集合
>>> s
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
计算元素个数
>>> s = {'youtube','twitter','instagram','facebook'}
>>> len(s) # len()方法是计算集合元素个数
4
判断元素是否在集合中
>>> s = {'youtube','twitter','instagram','facebook'}
>>> 'youtube' in s # 用in判断元素是否在集合中,存在则返回True,不存在则返回False
True
>>> 'yahoo' in s
False
其他方法
# copy() 方法用于拷贝一个集合。 >>> s = {'youtube','twitter','instagram','facebook'} >>> s1 = s.copy() >>> s1 {'twitter', 'facebook', 'instagram', 'youtube'} # difference() 方法用于返回集合的差集,即返回的集合元素包含在第一个集合中,但不包含在第二个集合(方法的参数)中。 # difference_update() 方法用于移除两个集合中都存在的元素。 # difference_update() 方法与 difference() 方法的区别在于 difference() 方法返回一个移除相同元素的新集合,而 difference_update() 方法是直接在原来的集合中移除元素,没有返回值。 >>> s1 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s11 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s2 = {"google","youtube","yahoo","twitter"} >>> s22 = {"google","youtube","yahoo","twitter"} >>> a = s1.difference(s2) >>> a {'facebook', 'instagram'} >>> b = s11.difference_update(s22) >>> b >>> s1 {'youtube', 'twitter', 'facebook', 'instagram'} >>> s11 {'facebook', 'instagram'} # intersection() 方法用于返回两个或更多集合中都包含的元素,即交集。 # intersection_update() 方法用于获取两个或更多集合中都重叠的元素,即计算交集。 # intersection_update() 方法不同于 intersection() 方法,因为 intersection() 方法是返回一个新的集合,而 intersection_update() 方法是在原始的集合上移除不重叠的元素。 >>> s1 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s11 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s2 = {"google","youtube","yahoo","twitter"} >>> s22 = {"google","youtube","yahoo","twitter"} >>> a = s1.intersection(s2) >>> a {'twitter', 'youtube'} >>> b = s11.intersection_update(s22) >>> b >>> s1 {'youtube', 'twitter', 'facebook', 'instagram'} >>> s11 {'twitter', 'youtube'} # isdisjoint() 方法用于判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。 >>> s1 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s2 = {"google","youtube","yahoo","twitter"} >>> s1.isdisjoint(s2) False # issuperset() 方法用于判断指定集合的所有元素是否都包含在原始的集合中,如果是则返回 True,否则返回 False。 # issubset() 方法用于判断集合的所有元素是否都包含在指定集合中,如果是则返回 True,否则返回 False。 >>> s1 = {"google","twitter","youtube","instargram"} >>> s2 = {"google","youtube"} >>> s1.issuperset(s2) True >>> s2.issubset(s1) True # symmetric_difference() 方法返回两个集合中不重复的元素集合,即会移除两个集合中都存在的元素。 # symmetric_difference_update() 方法移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。 >>> s1 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s11 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s2 = {"google","youtube","yahoo","twitter"} >>> s22 = {"google","youtube","yahoo","twitter"} >>> a = s1.symmetric_difference(s2) >>> a {'facebook', 'instagram', 'google', 'yahoo'} >>> b = s11.symmetric_difference_update(s22) >>> b >>> s1 {'youtube', 'twitter', 'facebook', 'instagram'} >>> s11 {'facebook', 'instagram', 'google', 'yahoo'} # union() 方法返回两个集合的并集,即包含了所有集合的元素,重复的元素只会出现一次。 >>> s1 = {'twitter', 'facebook', 'instagram', 'youtube'} >>> s2 = {"google","youtube","yahoo","twitter"} >>> s1.union(s2) {'facebook', 'instagram', 'google', 'youtube', 'yahoo', 'twitter'}
字典(dict)
字典是一个无序、可变和有索引的集合,用花括号编写,拥有键和值,每个键值对用冒号分割,每个对之间用逗号分隔,如:
d = {'name':'Star','sex':'male','age':23,'hobby':'play game'}
键必须是唯一的 ,但值不必。值可以取任何数据类型,但键必须是不可变的,如字符串,数字和元组。
访问字典里的值
把相应的键放入括号内,如:
>>> d = {'name':'Star','sex':'male','age':23,'hobby':'play game'
>>> d['name']
'Star'
>>> d['age']
23
如果字典里没有键访问数据,会输出错误:
>>> d = {'name':'Star','sex':'male','age':23,'hobby':'play game'}
>>> d['class']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'class'
通过get()方法也可以通过键来访问值,且键不存在时,可以返回None,或者自己指定的值:
>>> d = {'name':'Star','sex':'male','age':23,'hobby':'play game'}
>>> d.get('name')
'Star'
>>> d.get('class',1)
1
更改字典
向字典添加新内容的方法是增加新的键值对,更改值则可以通过键名来更改,如:
>>> d = {'name':'Star','sex':'male','age':23,'hobby':'play game'}
>>> d['class'] = 1
>>> d['sex'] = 'female'
>>> d
{'name': 'Star', 'sex': 'female', 'age': 23, 'hobby': 'play game', 'class': 1}
删除字典元素
有几种方法可以从字典中删除项目:
>>> d = {'name': 'Star', 'sex': 'female', 'age': 23, 'class': 1, 'hobby' : 'play games'}
>>> d.pop('hobby') # pop()方法删除具有指定键名的元素
'play games'
>>> d
{'name': 'Star', 'sex': 'female', 'age': 23, 'class': 1}
>>> d.popitem() # popitem()方法删除最后一个的元素
('class', 1)
>>> d
{'name': 'Star', 'sex': 'female', 'age': 23}
>>> del d['age'] # del 删除具有指定键名的元素
>>> d
{'name': 'Star', 'sex': 'female'}
>>> d.clear() # clear()方法清空字典
>>> d
{}
>>> del d # del 也可以完全删除字典
>>> d
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
字典的嵌套
字典中也可以包含字典,如:
>>> classmates = {'classmate1':{'name':'jack','age':20},'classmate2':{'name':'lili','age':22},'classmate3':{'name':'Star','age':23}}
或者,嵌套三个已经作为字典存在的字典:
>>> classmate1 = {'name':'jack','age':20}
>>> classmate2 = {'name':'lili','age':22}
>>> classmate3 = {'name':'Star','age':23}
>>> classmates = {'classmate1':classmate1,'classmate2':classmate2,'classmate3':classmate3}
>>> classmates
{'classmate1': {'name': 'jack', 'age': 20}, 'classmate2': {'name': 'lili', 'age': 22}, 'classmate3': {'name': 'Star', 'age': 23}}
其他方法
# len()方法计算字典元素个数,即键的个数 >>> d = {'name':'Star','sex':'male','age':23,'class':1,'hobby':'play game'} >>> len(d) 5 # str()方法输出字典,以字符串表示 >>> str(d) "{'name': 'Star', 'sex': 'male', 'age': 23, 'class': 1, 'hobby': 'play game'}" # copy()方法返回一个字典的浅复制 >>> a = d.copy() >>> a {'name': 'Star', 'sex': 'male', 'age': 23, 'class': 1, 'hobby': 'play game'} # fromkeys()方法用于创建一个新字典 >>> x = ('key1','key2','key3') >>> d1 = dict.fromkeys(x) >>> d1 {'key1': None, 'key2': None, 'key3': None} >>> d1 = dict.fromkeys(x,10) >>> d1 {'key1': 10, 'key2': 10, 'key3': 10} # update()把字典d2的键值对更新到d中 >>> d2 = {'adress':'Sichuan'} >>> d.update(d2) >>> d {'name': 'Star', 'sex': 'male', 'age': 23, 'class': 1, 'hobby': 'play game', 'adress': 'Sichuan'} # items()方法以列表返回可遍历的元组数组 >>> d.items() dict_items([('name', 'Star'), ('sex', 'male'), ('age', 23), ('class', 1), ('hobby', 'play game'), ('adress', 'Sichuan')]) # keys()方法返回一个所有键的迭代器 >>> d.keys() dict_keys(['name', 'sex', 'age', 'class', 'hobby', 'adress']) # values()方法返回一个所有值的迭代器 >>> d.values() dict_values(['Star', 'male', 23, 1, 'play game', 'Sichuan']) # setdefault()方法和get()方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值 >>> d.setdefault('name') 'Star' >>> print(d.setdefault('phone')) None >>> d {'name': 'Star', 'sex': 'male', 'age': 23, 'class': 1, 'hobby': 'play game', 'adress': 'Sichuan', 'phone': None}
posted on 2020-04-20 10:52 MidSummer丶 阅读(173) 评论(0) 收藏 举报
浙公网安备 33010602011771号