集合

1.集合元素之间无序,每个元素唯一,不存在相同元素
2.集合元素不可更改,不能是可变数据类型
集合用{}表示,元素间用,分隔
建立集合类型用{}或者set() .建立空集合类型,必须用set(),因为空的{}是默认生成字典类型的

 

 

 

 

复制代码
>>> s = {'a','b',123}
>>> t = set('abab123')
>>> s|t
{'b', '3', 'a', '1', '2', 123}
>>> t
{'b', '3', '1', '2', 'a'}
>>> s-t
{123}
>>> t-s
{'2', '3', '1'}
>>> s&t
{'b', 'a'}
>>> s^t
{'1', '2', 123, '3'}
>>> s<=t
False
>>> s>t
False
>>> 
复制代码
复制代码
>>> s = {'a','b',123}
>>> s.add('c')
>>> s
{123, 'c', 'b', 'a'}
>>> s.discard('d')#删除一个元素,不存在也不会报错
>>> s
{123, 'c', 'b', 'a'}
>>> s.remove('d')
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    s.remove('d')
KeyError: 'd'
>>> s.clear()
>>> s
set()
>>> p = s.pop()
Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    p = s.pop()
KeyError: 'pop from an empty set'
>>> s = set('sdvfb')
>>> p =s.pop() #随机返回a的一个元素,更新a(从a中删除该元素),若a为空产
KeyError异常
>>> p
'b'
>>> s
{'v', 's', 'f', 'd'}
复制代码
复制代码
>>> p = s.copy()
>>> p
{'d', 'f', 's', 'v'}
>>> len(s)
4
>>> 'd' in s
True
>>> 'd'not in s
False
>>> set(cd)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    set(cd)
NameError: name 'cd' is not defined
>>> set('sf')# set(x) :将其它类型变量x转化为集合类型
{'s', 'f'}
复制代码
>>> a = {'p','y',123}
>>> for i in a:
    print(i,end='')

    
p123y

 

复制代码
#数据去重
>>> ls =['l','l','s','s',123]
>>> ls
['l', 'l', 's', 's', 123]
>>> s =set(ls)
>>> s
{'l', 123, 's'}
>>> lt = list(s)
>>> lt
['l', 123, 's']
复制代码

 

 

from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print(nums)

{0, 1, 2, 3, 4, 5}#{}的形式

posted on   cltt  阅读(228)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2018-11-17 hdu 5667
2018-11-17 华东交通大学2018年ACM“双基”程序设计竞赛 K
2018-11-17 华东交通大学2018年ACM“双基”程序设计竞赛 D
2018-11-17 map
2018-11-17 次小生成树
2018-11-17 set
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示