美文网首页
【09】集合

【09】集合

作者: Z_JoonGi | 来源:发表于2019-03-17 13:21 被阅读0次

1.什么是集合(set)

  • python内置的容器型数据类型.可变(支持增删),无序(不支持下标操作)
  • {元素1,元素2,元素3...}
  • 元素要求是不可变并且唯一
set1 = {1, 2, 3, 'abc', 100, (1, 2), 1, 1}
print(set1, type(set1))
注意:空集合: set()
set3 = set()
print(type(set3))

2.增删改查

2.1查

  • 集合没有办法单独取出某一个元素;只能遍历

    for item in set1:
    print(item)

2.2 增

1) set.add(元素)

在集合中添加指定的元素

set2 = {100, 2, 5, 20}
set2.add(200)
print(set2)
2)set.update(序列)

将序列中的元素(不可变的)添加到集合中

set2.update('abc')
print(set2)

set2.update({'aa': 11, 'bb': 22, 'a': 100})
print(set2)

2.3 删

1)set.remove(元素)

删除集合中指定元素, 元素不存在会报错

set2 = {100, 2, 5, 20}
set2.remove(100)
print(set2)
2)集合.clear()

清空集合

set2.clear()
print(set2)

2.4 改 (集合不支持改操作)

3.数学集合运算(重点)

3.1 包含关系

  • 集合1 >= 集合2
    判断集合1中是否包含集合2
  • 集合1 <= 集合2
    判断集合2中是否包含集合1
print({100, 2, 3, 200, 300, 400, 1} >= {1, 2, 3})

3.2 并集(|)

  • 集合1 | 集合2
    将集合1和集合2中的元素合并在一起产生新的集合(会去重)
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3, 8, 9, 10}
print(set1 | set2)

3.3交集(&)

  • 集合1 & 集合2
print(set1 & set2)

3.4差集(-)

  • 集合1 - 集合2
    集合1中除了和集合2公共的元素以外的元素
print(set1 - set2)

3.5补集(^)

print(set1 ^ set2)

4.相关的操作

1) in / not in

print(1 in {1, 2, 3})

2) set()

print(set([19, 23, 19, 0, 0, 0, 0]))

总结:集合的应用主要表现在去重和数据集合运算

练习: 用三个列表表示三门学科的选课学生姓名(一个学生可以同时选多门课),

  1. 求选课学生总共有多少人
  2. 求只选了第一个学科的人的数量和对应的名字
  3. 求只选了一门学科的学生的数量和对应的名字
  4. 求只选了两门学科的学生的数量和对应的名字
  5. 求选了三门学生的学生的数量和对应的名字
    names1 = ['name1', 'name2', 'name3', 'name4', 'name5', 'name6']
    names2 = ['name1', 'name2', 'name7', 'name8', 'name9', 'name10']
    names3 = ['name2', 'name3', 'name4', 'name7', 'name11', 'name12']
total0 = set(names1) | set(names2) | set(names3)
print('选课学生总共有多少人:%d' % len(total0))

total = set(names1) - set(names2) - set(names3)
total = set(names1) - (set(names2) | set(names3))
print('只选了第一个学科的人的数量:%d,对应的名字:%s' % (len(total), str(total)[1:-1]))

total1 = (set(names1) ^ set(names2) ^ set(names3)) - (set(names1) & set(names2) & set(names3))
print('只选了一门学科的学生的数量:%d, 对应的名字:%s' % (len(total1), str(total1)[1:-1]))


total2 = total0 - total1 - (set(names1) & set(names2) & set(names3))
print('只选了两门学科的学生的数量:%d, 对应的名字:%s' % (len(total2), str(total2)[1:-1]))

total3 = set(names1) & set(names2) & set(names3)
print('选了三门学科的学生的数量:%d, 对应的名字:%s' % (len(total3), str(total3)[1:-1]))

相关文章

网友评论

      本文标题:【09】集合

      本文链接:https://www.haomeiwen.com/subject/smfumqtx.html