容器型数据类型
set
{}
性质:
无序性:每个元素在集合中地位是一样的
互异性:一个集合中,一个元素只能存在一次
确定性:给定一个元素,该元素属于或者不属于这个集合
# 集合的创建方式
a = set()
print(type(a))
# 字典的创建方式
b = {}
print(type(b))
# add()
a.add(33)
# a.add({12, 32}) # 报错
print(a)
# updata
a.update({1, 20, 3})
print(a)
add()只能一个一个的添加,updata()添加元素可以放入徐两列中直接添加
# remove()
a.remove(33)
print(a)
# pop():随机删除一个集合中的元素
# 在cmd中是随机删除一个元素,但是Python不是
# 如果是字符串则删除最左边的元素
# 如果是数字,删除最小的数值
a.pop()
print(a)
c = {'Python', 'java', 'Go', 'C++', 'C#'}
print(c)
c.pop()
print(c)
c.clear()
print(c)
e = set('hello')
print(e)
for i in e:
print(i)
f = {i for i in range(1, 11)}
print(f)
print(1 in f)
set1 = {4, 7, 9, 12, 56}
set2 = {4, 7, 12, 32}
print(set1 & set2)
print(set1.intersection(set2))
print(set1 | set2)
print(set1.union(set2))
print(set1 - set2)
print(set2 - set1)
print(set1.difference(set2))
print(set1 ^ set2)
print(set1.symmetric_difference(set2))
set3 = {20, 15, 32, 42}
set4 = {20, 15}
print(set4 < set3)
print(set4 <= set3)
字典
{}
dict
字典中的元素是以键值对方式存在的,key:value
dict_1 = {}
字典中的键必须是不可变类型:字符串、数字、组元
字典的值可以是任意类型
dict_2 = {'name': '小明', 'age': 20}
print(dict_2)
dict_3 = dict(name='蘑菇', age=30)
print(dict_3)
dict_4 = dict(zip('ABCDE', '12345'))
print(dict_4)
dict_5 = dict(zip('ABCDE', range(1, 11)))
print(dict_5)
dict_6 = {i: i ** 3 for i in range(1, 6)}
print(dict_6)
a = dict_2['name']
print(a)
# 如果找的键不存在,报错
# b = dict_2['zone']
# print(b)
dict_2['name'] = '猪小妹'
print(dict_2)
# 如果替换字典中不存在的键的值,等于添加
dict_2['zone'] = '123'
print(dict_2)
for i in dict_2:
print(i, '--->', dict_2[i])
print(len(dict_2))
print(dict_2.keys())
print(dict_2.values())
print(dict_2.items())
for key, value in dict_2.items():
print(key, '--->', value)
a = dict_2.pop('zone')
print(a)
print(dict_2)
# 如果字典为空,报错,ketError
b = dict_2.popitem()
print(b)
print(dict_2)