python数据类型之元组、字典、集合

python数据类型元组、字典、集合

元组

python的元组与列表类似,不同的是元组是不可变的数据类型。元组使用小括号,列表使用方括号。当元组里只有一个元素是必须要加逗号:

>>> x = (1,)
>>> type(x)
<class 'tuple'>
>>> y =(1)
>>> type(y)
<class 'int'>
>>> z = 1,
>>> type(z)
<class 'tuple'>
>>> z = 1,2
>>> type(z)
<class 'tuple'>
>>> 

元组的特性:

  • 不可变

  • 可存放多个值

  • 按照从左到右的顺序定义元组元素,下标从0开始顺序访问,有序

元组创建

元组创建可以直接在括号里添加元素,也可以直接逗号赋值创建,还可以使用tuple函数,默认创建就是去调用tuple函数:

>>> tup1 = {'tom','jack','rain'}
>>> tup1 = ('tom','jack','rain')
>>> tup2 = (1,2,3,4,5)
>>> tup3 = 'a','b','c','d'
>>> type(tup1)
<class 'tuple'>
>>> type(tup2)
<class 'tuple'>
>>> type(tup3)
<class 'tuple'>
>>> 
>>>> m = ['a','b','c']
>>> n = tuple(m)
>>> n
('a', 'b', 'c')
>>> 

创建空元组:

>>> tup = ()
>> type(tup)
<class 'tuple'>
>>> 

元组常用操作

索引和切片:

>>> x=(1,2,3,4,5)
1
>>> x[::-1]
(5, 4, 3, 2, 1)
>>> x[-2:]
(4, 5)
>>> x[::2]
(1, 3, 5)
>>> 

循环:

>>> x=(1,2,3,4,5)
>>> for i in x:
		print(i)	
	1
2
3
4
5
>>> 

长度:

>>> x=(1,2,3,4,5)
>>> len(x)
5
>>>

成员运算(包含)

>>> x=(1,2,3,4,5)
>>> 1 in x
True
>>> '1' in x
False
>>> 

字典

定义:{key1:value1,key2:value2},key-value结构,key必须可hash,即是key必须是不可变类型:
字典的特性:

  • 可存放多个值(键值对items)
  • 可修改指定key对应的值,可变
  • 无序

字典创建

person = {"name": "lucy", 'age': 18}

person = dict(name='lucy', age=18)
person = dict({"name": "lucy", 'age': 18})
person = dict((['name','lucy'],['age',18]))
person = dict((('name','bob'),('age',18)))
{}.fromkeys(seq,100) #不指定100默认为None
注意:

>>> dic={}.fromkeys(['k1','k2'],[])
>>> dic
{'k1': [], 'k2': []}
>>> dic['k1'].append(1)
>>> dic
{'k1': [1], 'k2': [1]} 

字典常用操作

索引
因为字典是无序的,所以访问字典的值是通过键值来索引访问。

>>> dict1 = {'name': 'bob', 'age': 16, 'gender': 'male'}
>>> dict1['name']
'bob'
>>> dict1['age']
16

但是当输入的索引键在字典中没有会报错:

>>> dict1 = {'name': 'bob', 'age': 16, 'gender': 'male'}
>>> dict1['Age']
Traceback (most recent call last):
File "<pyshell#110>", line 1, in <module>
dict1['Age']
KeyError: 'Age'

程序里我们可以使用get()去访问字典中的值,即使键值字典里没有也不会报错。找到了就返回value,找不到默认不返回任何信息,可以自定义返回信息内容

>>> dict1 = {'name': 'bob', 'age': 16, 'gender': 'male'}
>>> dict1.get('Age')
>>> 
>>> dict1.get('Age',-1)
-1
>>> dict1.get('Age','找不到')
'找不到'
>>> dict1.get('age')
16
>>> 

新增和更新
增加items只需要直接赋值即可,更新也是一样的:

>>> d1 = {}
>>> d1['name'] = 'tom'
>>> d1['age'] = 18
>>> d1
{'name': 'tom', 'age': 18}
>>> d1['age'] = 20
>>> d1
{'name': 'tom', 'age': 20}
>>> 	

删除
del删除不会返回任何信息,删除键值不存在的会报错。

>>> d1
{'name': 'tom', 'age': 20}
>>> del d1['age']
>>> d1
{'name': 'tom'}
>>> del d1['Age']
Traceback (most recent call last):
File "<pyshell#124>", line 1, in <module>
del d1['Age']
KeyError: 'Age'
>>> 

pop()删除和popitem()
pop()删除字典给定键 key 所对应的值,返回值为被删除的值。

>>> d1 = {'name': 'tom', 'age': 18}
>>> d1
{'name': 'tom', 'age': 18
>>> d1.pop('age')
18
>>> d1
{'name': 'tom'}
>>>

popitem()随机返回并删除字典中的一对键和值

>>> d1 = {'name': 'tom', 'age': 18}
>>> d1.popitem()
('age', 18)
>>> 

循环

dict1 = {'name':'tom','age':20,'gender':'male','hobbie':'music'}
for i in dict1:
	print(i)

运行结果:
name
age
gender
hobbie

for i in 字典 和 for i in 字典.keys()是一样的作用,都是遍历字典的键。

for i in 字典.items() 可以循环遍历字典的键值对:

	dict1 = {'name':'tom','age':20,'gender':'male','hobbie':'music'}
	for i in dict1.items():
		print(i)

运行结果:
('name', 'tom')
('age', 20)
('gender', 'male')
('hobbie', 'music')

	dict1 = {'name':'tom','age':20,'gender':'male','hobbie':'music'}
	for k,v in dict1.items():
		print('dict1[%s]=%s' %(k,v))

运行结果:
dict1[name]=tom
dict1[age]=20
dict1[gender]=male
dict1[hobbie]=music

长度

>>> d1 = {'name': 'tom', 'age': 18}	
>>>> len(d1)
2
>>> len(d1.keys())
2	
>>> len(d1.values())
2
>>> 

集合

set是基本数据类型的一种集合类型,是一个无序不重复元素集。它有可变集合(set())和不可变集合(frozenset)两种。创建集合set、集合set添加、集合删除、交集、并集、差集的操作都是非常实用的方法。
集合的创建
创建一个数组集合:

>>> s1 = set([1,3,5,7,8])
>>> type(s1)
<class 'set'>
>>> s1
{1, 3, 5, 7, 8}
>>> 

创建字符集合:

>>> s2 = set('Hello')
>>> type(s2)
<class 'set'>
>>> s2
{'l', 'H', 'e', 'o'}
>>>

上面的字符集合,里面只有一个'l'

集合常用操作

交集,并集,差集,对称差集

a = t | s        # t 和 s的并集
b = t & s        # t 和 s的交集
c = t – s        # 求差集(项在t中,但不在s中)
d = t ^ s        # 对称差集(项在t或s中,但不会同时出现在二者中)

添加
添加一项:

>>> s1 = set([1,3,5,7,8])
>>> s1.add(10)
>>> s1
{1, 3, 5, 7, 8, 10}
>>> 

添加多项:

>>> s1 = set([1,3,5,7,8])
>>> s1.update([11,12,13])
>>> s1
{1, 3, 5, 7, 8, 11, 12, 13}
>>> 

删除
删除一项,如果果不存在则报错,不报错可以使用discard(),discard删除元素,如果集合中有这个元素就删除,没有也不会报错。pop()随机删除集合的一个元素,返回值为随机删除的元素,集合为空时pop()会报错。 删除整个集合使用clear()

>>> s1 = {1, 3, 5, 7, 8,13}
>>> s1
{1, 3, 5, 7, 8, 13}
>>> s1.remove(13)
>>> s1
{1, 3, 5, 7, 8}
>>> s1.remove(14)
Traceback (most recent call last):
File "<pyshell#172>", line 1, in <module>
s1.remove(14)
KeyError: 14
>>> s1.discard(14)
>>> s1.discard(13)
>>> s1.discard(8)
>>> s1
{1, 3, 5, 7}

长度
集合的长度:

>>> s1 = {1, 3, 5, 7, 8,13}
>>> len(s1)
6
>>> 

成员运算

>>> s1 = {1, 3, 5, 7, 8,13}
>>> 5 in s1
True
>>> '5' in s1
False
>>> 

子集

>>> s1 = {'a','b','c'}
>>> s2 = {'a','b','c','d'}
>>> s1.issubset(s2)
True
>>> 

父集

>>> s1 = {'a','b','c'}
>>> s2 = {'a','b','c','d'}
>>> s2.issuperset(s1)
True
>>> 

交集
等价于 s1 & s2

>>> s1 = {'a','b','c','d'}
>>> s2 = {'a','c','e','f'}
>>> s1.intersection(s2)
{'c', 'a'}

并集
等价于 s1 | s2

>>> s1 = {'a','b','c','d'}
>>> s2 = {'a','c','e','f'}
>>> s1.union(s2)
{'b', 'e', 'd', 'c', 'f', 'a'}
>>> 

差集
等价于 s1 - s2

>>> s1 = {'a','b','c','d'}
>>> s2 = {'a','c','e','f'}
>>> s1.difference(s2)
{'b', 'd'}
>>> 

对称差集
等价于 s1 ^ s2

>>> s1 = {'a','b','c','d'}
>>> s2 = {'a','c','e','f'}
>>> s1.symmetric_difference(s2)
{'b', 'f', 'e', 'd'}
>>>
posted @ 2017-06-09 23:30  村口王铁匠  阅读(389)  评论(0编辑  收藏  举报