您的位置:首页 > 编程语言 > Python开发

python set集合

2016-01-25 11:30 986 查看
说明:集合对象是一组无序排列的哈希的值,集合成员可以做字典中的键;

集合支持用in 和not in 操作符检查成员,由len()内建函数得到集合的大小,用for 循环迭代集合的成员,但是因为集合无序,所以不能通过创建索引或执行切片操作,也没有键可以用来获取集合中元素的值。除无序以外,集合内的元素不能重复

集合分为可变集合(set)和不可变集合(forzenset)。对于可变集合,可以用来添加和删除元素,但不可用来哈希,不能用来做字典的键,也不能做其他集合的元素。

不可变集合则相反,有哈希,可以添加删除,能被用来做字典的键和集合中的一员。

另外支持union(联合),intersection(交),difference(差),和sysmmetric difference(对称差集)等数学运算。

 

 

1:如何创建集合和给集合赋值:通过集合唯一的方法,set()和frozenset()

s
= set('test')
print(s)
print(type(s))
print(len(s))

#### 输出结果
{'s',
't',
'e'}
<class
'set'>
3
 

2:如何访问集合中的值

s = set('thisistest')
print('k' in s)
print('t' in s)
print('a' in s)
for i in s:
    print(i)

#### 输出结果
False
True
False
h
i
e
t
s

 

 

集合方法:

1: set 类方法

class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
   
    Build an unordered collection of unique elements.
    """

 

2:add --: 添加 元素集

def add(self, *args, **kwargs): # real signature unknown
    """
    Add an element to a set.
   
    This has no effect if the element is already present.
    """
    pass

使用方法:

s = set('thisistest')
print(s)
s1 = s.add('zzzz')
print(s)

#### 输出结果
{'t', 's', 'e', 'i', 'h'}
{'zzzz', 's', 't', 'e', 'i', 'h'}

 

3: clear-------清空

def
clear(self,
*args,
**kwargs):
# real signature unknown

    """ Remove allelements from this set. """

    pass
使用方法:

s
= set('thisistest')
print(s)
print(s.clear())

#### 输出结果
{'e',
't',
'i',
'h',
's'}
None
 

4: copy-------复制

def
copy(self,
*args,
**kwargs):
# real signature unknown

    """ Return a shallowcopy of a set. """

    pass
使用方法:

s = set('thisistest')
s1 = s.copy()
print("s:",s)
print("s1:",s1)

#### 输出结果
s: {'t', 'h', 'i', 'e', 's'}
s1: {'t', 'h', 'i', 'e', 's'}

 

5: difference ---- 对比set集合,返回值中没有的元素形成一个新的set集合

def difference(self, *args, **kwargs): # real signature unknown
    """
    Return the difference of two or more sets as a new set.
   
    (i.e. all elements that are in this set but not the others.)
    """
    pass

使用方法:

s = set('thisistest')
s1 = set('mynameistest')
s2 = s.difference(s1)
print(s.difference(s1))
print(type(s2))

#### 输出结果
{'h'}
<class 'set'>

 

6: difference_update --- 取差值元素,删除另一个集合中存在的元素

def difference_update(self, *args, **kwargs): # real signature unknown
    """ Remove all elements of another set from this set. """
    pass

使用方法:

s= set('thisistest')
s1 = set('mynameistest')
s2 = s.difference(s1)
print(s.difference_update(s1))
print(s)

#### 输出结果
None
{'h'}

 

7:discard --- 删除元素,如果存在元素,则删除

def discard(self, *args, **kwargs): # real signature unknown
    """
    Remove an element from a set if it is a member.
   
    If the element is not a member, do nothing.
    """
    pass

使用方法:

s = set('thisistest34')
s1 = set('this')
print("old:",s)
s.discard('t')

print("new:",s)

#### 输出结果
old: {'t', 'h', '3', 's', 'e', '4', 'i'}
new: {'h', '3', 's', 'e', '4', 'i'}

 

 

8:intersection --- 交集:返回两个集合的交集

def intersection(self, *args, **kwargs): # real signature unknown
    """
    Return the intersection of two sets as a new set.
   
    (i.e. all elements that are in both sets.)
    """
    pass

使用方法:

s = set('thisistest34mymynameistest')
s1 = set('mynameistest')
s2 = s.intersection(s1)
print(s)
print(s2)
print(s1)

#### 输出结果
{'t', 's', 'n', 'e', 'y', 'h', 'a', 'm', '3', 'i', '4'}
{'t', 'n', 's', 'e', 'y', 'a', 'm', 'i'}
{'t', 'n', 's', 'e', 'y', 'a', 'm', 'i'}

 

9:intersection_update 对比元素,只更新self,只保留和值中共同存在的元素

def intersection_update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the intersection of itself and another. """
    pass

使用方法:

s= set('thisistest34')
s1 = set('mynameistest')
s.intersection_update(s1)
print(s)
print(s1)

#### 输出结果
{'t', 'e', 's', 'i'}
{'e', 's', 'n', 'm', 't', 'i', 'a', 'y'}

 

10: isdisjoint --- 如果有一个集合为空,则返回True

def isdisjoint(self, *args, **kwargs): # real signature unknown
    """ Return True if two sets have a null intersection. """
    pass

使用方法:

s = set('thisistest34')
s1 = set('')

print(s.isdisjoint(s1))

#### 输出结果
True

 

10:issubset ----  判断另一个集合是否包含,返回bool值

def issubset(self, *args, **kwargs): # real signature unknown
    """ Report whether another set contains this set. """
    pass

使用方法:

s = set('thisistest34')
s1 = set('this')

print(s.issubset(s1))
print(s1.issubset(s))

#### 输出结果
False
True

 

11:issuperset --- 判断自身是否包含另一个集合,返回bool值

def issuperset(self, *args, **kwargs): # real signature unknown
    """ Report whether this set contains another set. """
    pass

使用方法:

s = set('thisistest34')
s1 = set('this')

print(s.issuperset(s1))
print(s1.issuperset(s))

#### 输出结果
True
False

 

12:pop --- 删除任意元素并返回其值

def pop(self, *args, **kwargs): # real signature unknown
    """
    Remove and return an arbitrary set element.
    Raises KeyError if the set is empty.
    """
    pass

使用方法:

s= set('thisistest34')
s1 = set('this')

print(s.pop())
print(s)

#### 输出结果
3
{'t', 'h', 'e', '4', 'i', 's'}

### 再次执行
s
{'i', 'h', 't', '4', 'e', '3'}

 

13: remove ---删除元素,如果元素不存在,将报错

def remove(self, *args, **kwargs): # real signature unknown
    """
    Remove an element from a set; it must be a member.
   
    If the element is not a member, raise a KeyError.
    """
    pass

使用方法:

s = set('thisistest34')
s1 = set('this')
s.remove('t')
#print(s.pop())
print(s)

#### 输出结果
{'h', 'e', 'i', '4', '3', 's'}

 

14: symmetric_difference --- 返回两个集合的不同元素

def symmetric_difference(self, *args, **kwargs): # real signature unknown
    """
    Return the symmetric difference of two sets as a new set.
   
    (i.e. all elements that are in exactly one of the sets.)
    """
    pass

使用方法:

s= set('thisistest34')
s1 = set('this')
s2 = s.symmetric_difference(s1)
#print(s.pop())
print(s2)

#### 输出结果
{'3', 'e', '4'}

 

 

15:symmetric_difference_update– 更新自己为两个集合的不相等元素

def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the symmetric difference of itself and another. """
    pass

使用方法:

s= set('thisistest34')
s1 = set('this')
s.symmetric_difference_update(s1)
#print(s.pop())
print("s:",s)

#### 输出结果
s: {'e', '3', '4'}

 

16: union --- 返回两个集合的并集生成一个新的集合

def union(self, *args, **kwargs): # real signature unknown
    """
    Return the union of sets as a new set.
   
    (i.e. all elements that are in either set.)
    """
    pass

使用方法:

s = set('thisistest34')
s1 = set('this56')
print("s:",s)
#print(s.pop())
print(s1.union(s))

#### 输出结果
s: {'h', '4', 't', 'i', 's', 'e', '3'}
{'6', '5', 'h', '4', 't', 'i', 's', 'e', '3'}

 

 

17:update -- : 添加多项至本身

def update(self, *args, **kwargs): # real signature unknown
    """ Update a set with the union of itself and others. """
    pass

使用方法:

s = set('thisistest34')
s1 = set('this56')
print("old:",s)
s.update(s1)

print("new:",s)

#### 输出结果
old: {'i', '3', 'e', 'h', '4', 't', 's'}
new: {'i', '3', 'e', 'h', '4', 't', '5', 's', '6'}

 

小实验:寻找差异

# 数据库中原有

old_dict = {
"#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 },
"#2":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
"#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
}


# cmdb 新汇报的数据

new_dict = {
"#1":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 800 },
"#3":{ 'hostname':c1, 'cpu_count': 2, 'mem_capicity': 80 }
"#4":{ 'hostname':c2, 'cpu_count': 2, 'mem_capicity': 80 }
}


需要删除:?
需要新建:?
需要更新:? 注意:无需考虑内部元素是否改变,只要原来存在,新汇报也存在,就是需要更新
 

操作方法:

old_set
= set(old_dict.keys())
print(old_set)

update_list = list(old_set.intersection(new_dict.keys()))
print("update_list:",update_list)

new_list = []

del_list = []

for i
in new_dict.keys():

    print("new_keys:",i)

    if i
not in update_list:

        new_list.append(i)

for i
in old_dict.keys():

    print("old_dict_key:"
,i)

    if i
not in update_list:
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: