赞
踩
# 1. 集合创建
# 1.1 使用{}创建集合
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3, 4, 5, 2, 3}
set3 = {1, 2, 'python', ('python', 'R'), (1, 2, 3)}
print('set1', set1)
print('set2', set2)
print('set3', set3)
创建集合的元素不能为可变对象,如:列表、字典、集合
set41 = {1,2,'python',('python','R'),[1,2,3]} #列表为可变对象
print('set41',set41)
set42 = {1,2,'python',('python','R'),{1,2,3}} #集合为可变对象
print('set42',set42)
set43 = {1,2,'python',('python','R'),{'apple':5,'orange':6}} # 字典为可变对象
print('set43',set43)
# 1.2 set()函数创建
set5 = set('明日复明日,明日何其多。')
set6 = set(['明日', '明日何其多'])
set7 = set(('明日', '明日何其多'))
set8 = set(range(5))
print('set5', set5)
print('set6', set6)
print('set7', set7)
print('set8', set8)
# 2.1 增加元素
print(set1)
set1.add('happy')
print('增加字符串happy', set1)
set1.add(8)
print('增加数字8', set1)
set1.add(('math', 90))
print('增加元组', set1)
# 2.2 删除
set1.remove('happy')
print('删除指定元素happy', set1)
set1.remove(8)
print('删除指定元素8', set1)
set1.clear()
print('清空集合set1: ', set1)
# 3. 集合运算
set9 = {1, 2, 'python', ('python', 'R')}
set10 = {'python', 1, 10}
print('输出set9与set10的交集: ', set9 & set10)
print('输出set9与set10的并集: ', set9 | set10)
print('输出set9-set10的差集: ', set9 - set10)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。