第八讲:集合和函数

在这里插入图片描述

一. 集合

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值