现在的位置: 首页 > 综合 > 正文

【python coding 5:集合】python中集合的用法

2018年01月26日 ⁄ 综合 ⁄ 共 773字 ⁄ 字号 评论关闭

 python中集合的用法,归纳如下:

 

#!/bin/env python
#---(1)用集合的工厂方法set()和frozenset()---
#set方法
>>> s = set('cheeseshop')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's'])
#frozenset方法
>>> t = frozenset('bookshop')
>>> t
frozenset(['b', 'h', 'k', 'o', 'p', 's'])
#type方法查看集合的类型
>>> type(s)
<type 'set'>
>>> type(t)
<type 'frozenset'>

#---(2)更新集合---
#使用集合的内建方法和操作符添加和删除集合的成员
#添加
>>> s.add('z')
>>> s
set(['c', 'e', 'h', 'o', 'p', 's', 'z'])
#更新
>>> s.update('pypi')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y', 'z'])
#删除
>>> s.remove('z')
>>> s
set(['c', 'e', 'i', 'h', 'o', 'p', 's', 'y'])
#使用-=删除字符
>>> s -= set('pypi')
>>> s
set(['c', 'e', 'h', 'o', 's'])
#删除集合 
del s

#---(3)成员关系---
# (in, not in) 
>>> s = set('cheeseshop')
>>> t = frozenset('bookshop')
>>> 'k' in s
False
>>> 'k' in t
True
>>> 'c' not in t
True

#---(4)集合等价/不等价
>>> s == t
False
>>> s != t
True
>>> u = frozenset(s)
>>> s == u
True
>>> set('posh') == set('shop')
True


 

抱歉!评论已关闭.