Python笔记
来源:互联网 发布:excel数据左上角 编辑:程序博客网 时间:2024/06/10 01:36
创建集合
备注:集合是无序的
- 用{}创建集合,元素用逗号隔开
>>> num = {}>>> type(num)<class 'dict'>>>> num2 = {1,2,3}>>> type(num2)<class 'set'>
- 用set() 创建集合
>>> set1 = set([1,2,3,4,5,3,2])>>> set1{1, 2, 3, 4, 5}
集合不允许重复,创建的集合自动去重复
>>> num2 = {1,2,3,4,5,3,2}>>> num2{1, 2, 3, 4, 5}
用set() 将其他类型转化为集合
将列表转化为集合时,原列表的顺序会发生改变
>>> num1 = [1,2,3,4,5,5,3,2,1,0]>>> num1 = set(num1)>>> num1{0, 1, 2, 3, 4, 5}
集合不允许通过索引查找
>>> num2 = {1,2,3,4,5,3,2}>>> num2[1]Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> num2[1]TypeError: 'set' object does not support indexing
使用 for 读取集合中的每个数据
>>> num1 = {1, 2, 3, 4, 5}>>> for each in num1: print(each,end = ' ')1 2 3 4 5
使用in和not in判断一个元素是否在集合中
>>> num2 = {1, 2, 3, 4, 5}>>> 1 in num2True>>> '1' in num2False
add() 函数
向集合中添加元素,无返回值
>>> num1 = {1, 2, 3, 4, 5}>>> num1.add(6)>>> num1{1, 2, 3, 4, 5, 6}
remove() 函数
移除集合中的元素,括号中传入要移除的元素,无返回值
>>> num1 = {1, 2, 3, 4, 5}>>> num1.remove(4)>>> num1{1, 2, 3, 5}>>> num1.remove(6) # 括号中的元素不在集合中,报错Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> num1.remove(6)KeyError: 6
frozenset() 设置不可变集合
使用此方法创建的集合不可改变
frozen:冰冻的,冻结的
>>> num1 = frozenset([1,2,3,4,5])>>> num1.add(0)Traceback (most recent call last): File "<pyshell#38>", line 1, in <module> num1.add(0)AttributeError: 'frozenset' object has no attribute 'add'
阅读全文
0 0
- Python笔记
- python笔记
- python笔记
- python笔记
- python笔记
- PYTHON笔记
- python笔记
- python笔记
- python笔记
- Python笔记
- Python笔记
- Python笔记
- PYTHON笔记
- Python笔记
- python笔记-------------
- python笔记
- Python笔记
- python 笔记
- Custom Container View Controller
- ubuntu16.04 编译安装kscope
- bash的配置文件~.profile
- Android跳转系统应用
- 黑幕背后的Autorelease
- Python笔记
- footer至于底部的四种方法
- NSValue对任何结构体,基本类型,指针的封装
- Scala入门到精通——第二十八节 Scala与JAVA互操作
- 访问控制符
- 微信检测工具 微信筛选技巧
- 在Swift中检查API的可用性
- Linux arm tftp 以及nfs 的调试方法使用
- Swift 多范式编程语言(对象,函数,协议)