Python集合
来源:互联网 发布:苹果系统检测软件 编辑:程序博客网 时间:2024/06/08 17:21
# -*- coding:UTF-8 -*-''' set是一个无序且不重复的元素集合'''def read_set(): # 创建set s1 = set('qiwsit') print s1 # s1= set(['q', 'i', 's', 't', 'w']) s2 = set([123, 'google', 'face', 'book', 'facebook', 'book']) # 通过list创建set,不能有重复元素 print s2 s3 = {'facebook', 123} # 通过{}直接创建 print s3 # 注意: # 通过{}无法创建含有list/dict元素的set # set不允许使用索引 # 通过list来进行索引 lst = list(s1) print lst print lst[3], lst[2] # 增加元素 a_set = {} print type(a_set) # 注意,此时类型为dict,<type 'dict'> b_set = {'a', 'i'} print type(b_set) # 此时类型为<type 'set'> b_set.add('ahd') print b_set # 添加一个元素之后的集合:set(['i', 'a', 'ahd']) # 删除元素 pop(), remove(), discard() print b_set # b_set= set(['i', 'a', 'ahd']) print b_set.pop() # 从set中删除一个元素 print b_set.pop() # 从set中删除一个元素 print b_set # set.pop() 从set中任意选一个元素,删除并将这个值返回,但是,不能指定删除某个元素 # set.remove() 从set中指定删除某个元素 print b_set.add('time') print b_set.add('hello') print b_set # b_set= set(['hello', 'ahd', 'time']) b_set.remove('ahd') # 指定删除某个元素 print b_set # set,discard() 如果删除的是set中的元素,则删除,否则,什么也不做 b_set.discard('and') # b_set中没有'and'元素,什么也不做,原样输出 print b_set # sets支持 x in set, len(set), for x in set # 作为一个无序的集合,sets不记录元素的位置和插入点 # sets不支持index,slice等操作 # 基本操作 x = set('jihite') y = set(['d', 'i', 'm', 'i', 't', 'e']) # 去重 print x print y # 交 print 'x & y:', x & y # 并 print 'x | y:', x | y # 差 print 'x - y:', x - y # 对称差 print 'x ^ y:', x ^ yif __name__ == '__main__': read_set()
0 0
- python 集合
- python集合
- python 集合
- [python]集合
- Python 集合
- Python 集合
- python集合
- Python集合
- Python--集合
- Python:集合
- Python 集合
- Python集合
- python集合
- python 集合
- python 集合
- Python 集合
- Python集合
- python-集合
- csdn博客中动态动画的创建,mac版本的实现步骤
- 总结笔记一。
- 图的深度优先遍历和广度优先遍历
- 所有的正整数排在所有负数前面
- 数组指针和指针数组
- Python集合
- 总结16
- C++成员指针 int A::*
- C函数指针应用之回调函数
- 面试遇到的问题 进程和线程以及通信方式
- VB.NET Socket5代理客户端链接 LHSocket5 Server源码
- 不带缓存的I/O操作(2)
- 关于FTP
- 学习记录