Home > Backend Development > Python Tutorial > python基础知识小结之集合

python基础知识小结之集合

WBOY
Release: 2016-06-10 15:07:07
Original
1271 people have browsed it

集合

特点:集合对象是一组无序排列的可哈希的值:集合成员可以做字典的键,与列表和元组不同,集合无法通过数字进行索引。此外,集合中的元素不能重复。

 定义

 set() -> new empty set object
 set(iterable) -> new set object
 s = {0}

Copy after login

应用:去重

 >>> lst1 = [1,1,2,2,3,4,2]
 >>> list(set(lst1))
 [1, 2, 3, 4]


Copy after login

常用操作

集合支持一系列标准操作,包括并集|、交集&、差集-和对称差集^
子集< <=及超集> >=
增删,清空操作

具体见如下代码例子

>>> lst1 = [1,2]
>>> lst2 = [2,3]
>>> a = set(lst1) #定义集合
>>> b = set(lst2)
>>> a,b
({1, 2}, {2, 3})
>>> a|b #取并集
{1, 2, 3}
>>> a&b #取交集
{2}
>>> a-b #取差集
{1}
>>> b-a #取差集
{3}
>>> list(a) #转换集合为列表,也可转为元组,如 tuple(a)返回 (1,2)
[1, 2]
>>> a < b #子集判断
False
>>> c = set([1])
>>> c
{1}
>>> c < a #子集判断
True
>>> c <= a #子集判断
True
>>> d = set([1,2,3])
>>> d > a #超集判断
True
>>> 
>>> d >= a #超集判断
True
>>> a,b
({1, 2}, {2, 3})
>>> a^b # 对称差集 
{1, 3}
>>> c
{1}
>>> d
{1, 2, 3}
>>> a^d # 对称差集 
{3}
>>> s = {0}
>>> type(s)
<class 'set'>
>>> 
>>> print(s, len(s)) #集合长度 
{0} 1
>>> s.add('1') #添加元素
>>> s
{0, '1'}
>>> s.update([2,3]) #添加多个元素
>>> s
{0, 2, 3, '1'}
>>> s.remove(2) #删除指定元素,如没有则报错
>>> s
{0, 3, '1'}
>>> s.pop() #随便删元素(貌似没什么用)
0
>>> s
{3, '1'}
>>> s.discard(3) #删除指定元素
>>> s
{'1'}
>>> s.clear() #清空集合
>>> s
set()
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template