Python基础(5)字典(dict)和集合类型(set,frozenset)

元组,列表,字典,集合的格式:

s1=(1,23,4)
print(type(s1))    #tuple 元组
s2=[1,2,5]
print(type(s2))    #<class 'list'>,list 列表
s3={1:'s2',2:'s4'}
print(type(s3))    #<class 'dict'> dict字典
s4={1,2,3,1,1.4}
print(type(s4))    #<class 'set'>,集合,可变集合,内容不可以重复
s5=frozenset({1,2,3})
print(type(s5))    #<class 'frozenset'> 不变集合,内容不可以重复
print(s4)

字典:

#coding=gbk
'''
Created on 2018年5月31日

@author: nobody
'''

#字典的使用方法dict
d={1:'food',2:'drink',3:'reading'}
print(d[1])
del d[2]#删除第2项
print(d)
d[4]='fruit'#add 
print(d)

for k in d.keys():
    print(k,end=" ")#输出key值
print()
for values in d.values():
    print(values ,end=" ")#输出对应的values值
print()
for items in d.items():
    print(items ,end=" ")#输出键值对
print('-------------')
d.pop(3)#输入键,删除对应值  
print(d)
s1={6:'work',4:'running'}
d.update(s1)  #增加一个键值对,修改相同的键值对
print(d) 
# d1=(1,2,3)
# d1.append(6)#AttributeError: 'tuple' object has no attribute 'append'
#             #元组数据不可更改
# print(d1)

字典常用方法

#集合,set为可变集合
s=set('hello')
print()
s2={1,5,8,19}
print(s&s2)#交集
print(s2|s)#并集
print(s-s2)#差集
print(type({}))#<class 'dict'>
#dict3={[1,2,3]:'hello'}此方法不能创建字典,由于列表是可变的,不可以hash
print(set([1,2,1,2,3]))#set是可变集合,而集合内数据是不可重复的,所以输出:{1, 2, 3}
print(d)

集合对象方法:


可变集合方法


猜你喜欢

转载自blog.csdn.net/qq_40587575/article/details/80533986