python set operation

来源:互联网 发布:游族网络董事长 编辑:程序博客网 时间:2024/05/21 18:50

Set can be converted to list by list(set)


add(elem)

Add element elem to the set.

remove(elem)

Remove element elem from the set. Raises KeyError if elem is not contained in the set.

discard(elem)

Remove element elem from the set if it is present.


Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets.

Set elements, like dictionary keys, must be hashable.

Binary operations that mix set instances with frozenset return the type of the first operand. 

For example: frozenset('ab') |set('bc') returns an instance of frozenset.


Python中set的用法 

标签: python语言list测试c
 17254人阅读 评论(0) 收藏 举报
 分类:
 

Python 的集合类型和 其他语言类似, 是一个无序不重复元素集,我在之前学过的其他的语言好像没有见过这个类型,基本功能包括关系测试和消除重复元素.集合对象还支持union(联合), intersection(交), difference(差)和sysmmetricdifference(对称差集)等数学运算,和我们初中数学学的集合的非常的相似。

 

1先看下python 集合 类型的不重复性,这方面做一些去重处理非常的好,比如我们要处理一些数据,想把重复的数据给
去掉,然后在操作的话,可以把它转换成集合类型,然后在由集合类型转换成其他的类型。

a = [2,3,4,2,1]
我们最终要实现的效果是:a = [1,2,3,4]
那我们要怎么实现呢。
1观察下这个列表,我们发现列表里有重复的元素存在,所以我们第一想到的就是去掉列表里的重复元素。
a = set(a)
print a

集合a的结果是:set([1, 2, 3, 4])
下一步要实现排序,我们又想到了一个比较简单的方法,因为集合没有排序方法,而列表有排序的方法,所以我们们把它转换成python 列表 的类型,调用列表的排序方法。
a = list(a)
a.sort()
print a

列表a的结果是:[1,2,3,4]

2union(联合), intersection(交), difference(差)
a = set('abcde')
b = set('bdcf')

求集合的交集:
a & b
结果是:set(['c', 'b', 'd'])

求差集:
a - b
结果是:set(['a', 'e'])

求联合:
a|b
结果是:set(['a', 'c', 'b', 'e', 'd', 'f'])
总结:python 集合和数学的集合概念比较像,经常用在数据的去重处理和一些数据的中转处理。


0 0
原创粉丝点击