上课笔记
一. 集合
1. 集合的简介
(1)表示方式:{}
s = {
1, 'hello'}
print(s, type(s))
# 输出
{
'hello', 1} <class 'set'>
(2)集合只能储存不可变对象,例如列表是可变对象,所以列表不能储存进集合
s1 = {
1, 'hello', [1, 2, 3]}
print(s)
# 错误
Traceback (most recent call last):
File "D:/PyCharmproject/第8讲/第八讲.py", line 3, in <module>
s1 = {
1, 'hello', [1, 2, 3]}
TypeError: unhashable type: 'list'
(3)集合中存储的对象是无序的
s1 = {
1, 'hello', 2}
print(s1)
# 三次输出
{
'hello', 1, 2}
{
1, 2, 'hello'}
{
'hello', 1, 2}
(4)集合不能出现重复元素,可以通过这个特性进行数据去重
s1 = {
1, 'hello', 2, 2, 2, 2, 2}
print(s1)
# 输出
{
1, 2, 'hello'}
li1 = [1, 2, 3, 4, 1, 2, 3, 4]
s2 = set(li1)
print(s2)
# 输出
{
1, 2, 3, 4}
(5)创建空集合:需要用到set函数,因为直接用{}创建的话,显示的是字典而不是集合
s = set()
print(type(s))
# 输出
<class 'set'>
s = {
}
print(type(s))
# 输出
<class 'dict'>
2. 集合的使用
(1)s.len():获取集合中元素的数量
s2 = {
1, 2, 3, 4, 2, 4, 5, 6}
print(len(s2))
# 输出
6
(2)s.add():向集合中添加元素
s3 = {
1, 'abc', 3, 4, 'hello'}
s3.add(2)
print(s3)
# 输出
{
1, 2, 3, 4, 'abc', 'hello'}
(3)s1.update(s2):将一个集合中的元素添加到另一个集合中(s2传到s1中)
s3 = {
1, 'abc', 3, 4, 'hello'}
s4 = {
4, 5, 6}
s3.upda