Detailed python set collection

Python  collection, and a collection of mathematical concepts, like, to hold non-repeating elements, namely elements of the collection are unique, different from each other.

Formally, dictionaries and the like, Python will set all the elements in a pair of braces {} in use between adjacent elements "," separated, as shown below:

{Element1, element2, ..., elementN}

 From the content point of view, the same collection, only store immutable data types, including plastic, float, string, tuple, can not be stored lists, dictionaries, a collection of these variable data types , otherwise Python interpreter throw a TypeError.

And to note that the data must be guaranteed to be unique, because for each set of data elements, will keep a 

 Python is provided a method of creating a set of two kinds of set, {} are used to create and use set () function to convert the list, and other types of data tuple set.

 

[root@kube set]# cat demo.py 
a = {1,2,1,'test','hi','test','one'}
print(type(a))
print(a)
[root@kube set]# py demo.py 
<class 'set'>
{'hi', 1, 2, 'one', 'test'}
[root@kube set]# 

 

 

set1 = set("c.biancheng.net")
set2 = set([1,2,3,4,5])
set3 = set((1,2,3,4,5))
print("set1:",set1)
print("set2:",set2)
print("set3:",set3)

 

Note that if you want to create an empty set, only use the set () function to achieve. Because direct use of a pair {}, Python interpreter will treat this as an empty dictionary.

 

python access set collection element

Since the elements of the collection is disordered, and therefore can not use the index to access elements to the list that. Python, the access to the collection element The most common method is to use a cyclic structure, one by one to read out the data set.

[Kube the root @ SET] # CAT demo.py 
A = {1,2,1, ' Test ' , ' Hi ' , ' Test ' , ' One ' }
 Print (type (A))
 for ELE in A: # traversal See
     Print (ELE, End = ' - ' ) 

del A # delete
 Print (A) 
[the root @ Kube SET] # Py demo.py 
< class  ' SET ' > 
1--2 - Hi - Test - One -Traceback (most recent call last):
  File "demo.py", line 7, in <module>
    print(a)
NameError: name 'a' is not defined
[root@kube set]# 

 

 

 Python set set of basic operations (add, delete, intersection, union, difference)

 Python  the SET collection of the most common operation is to add to the collection, delete elements, as well as doing the intersection between the set and the union, difference and other operations, this section will explain one by one concrete realization of these operations.

[root@kube set]# cat demo1.py 
a = {1,2,'three','four',(5,6)}
b = {1,8,'th','fo',(5,6)}
c = {1,2,'three','four',(5,6)}
d = {1,8,'th','fo',(5,6)}
a.add('hi') #Add () function to add, each time it receives a parameter 
b.remove (( 5,6 )) #remove deleted, each receive only one parameter
 Print (A)
 Print (B) 
[the root @ Kube SET] # Py the demo1 .py 
{. 1, 2, ' Four ' , (. 5,. 6), ' Hi ' , ' Three ' } 
{ . 1,. 8, ' TH ' , ' FO ' } 
[@ Kube the root SET] # 

 

 

 Python set to do a collection of intersection, union, difference operation

In Figure 1, there are two sets, respectively set1 = {1,2,3} and set2 = {3,4,5}, they are both the same element, there are different elements. In these two sets, for example, are made of different calculation results are shown in Table 1.

 

Table 1 Python set operation set
Arithmetic operations Operators Python meaning example
Intersection & Take two set of common elements >>> set1 & set2
{3}
Union | Take two set of all elements >>> set1 | set2
{1,2,3,4,5}
Difference set - Take a further element in the set is not set >>> set1 - set2
{1,2}
>>> set2 - set1
{4,5}
Symmetric difference ^ Taking a set of A and B does not belong to the elements of A & B >>> set1 ^ set2
{1,2,4,5}

 

 

[Kube the root @ SET] # CAT demo1.py 
A = {1,2, ' Three ' , ' Four ' , (5,6 )} 
B = {1,8, ' TH ' , ' FO ' , (. 5, . 6 )}
 Print (a & B) # intersection of
 Print (a | B) # collection request
 Print (a - B) # differencing sets
 Print (a ^ B) # find symmetric difference is that in addition to all the rest of the intersection 
[Kube the root @ SET] # Py demo1.py 
{(. 5,. 6),. 1 } 
{ . 1, 2, ' Three ' , (. 5,. 6),. 8,'th', 'four', 'fo'}
{'four', 2, 'three'}
{'fo', 2, 'three', 'four', 8, 'th'}
[root@kube set]# 

 

 

 Detailed Python set collection method

>>> dir(set)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__iand__', '__init__', '__init_subclass__', '__ior__', '__isub__', '__iter__', '__ixor__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__',__rand__'', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'add', 'clear', 'copy', 'difference', 'difference_update', 'discard', 'intersection', 'intersection_update', 'isdisjoint', 'issubset', 'issuperset', 'pop', 'remove', 'symmetric_difference', 'symmetric_difference_update', 'union', 'update']
>>> 

Concrete syntax structure and function of each method are shown in Table 1.

 

Table. 1  the Python  SET Method
Method name Syntax Features Examples
add() set1.add() Adding numbers, strings, Boolean or tuple set to set1 >>> set1 = {1,2,3}
>>> set1.add((1,2))
>>> set1
{(1, 2), 1, 2, 3}
clear() set1.clear() Empty set1 a collection of all the elements = {L, 2,3} setl >>>
>>> set1.clear ()
>>> setl
SET ()

SET () represents only an empty set {} is the empty dictionary
copy() set2 = set1.copy() Set1 set2 set to Copy >>> set1 = {1,2,3}
>>> set2 = set1.copy()
>>> set1.add(4)
>>> set1
{1, 2, 3, 4}
>>> set1
{1, 2, 3}
difference()  set3 = set1.difference(set2) The set1 and set2 there is no element to set3 >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set3 = set1.difference(set2)
>>> set3
{1, 2}
difference_update() set1.difference_update(set2) Delete the same elements from set2 set1 in >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set1.difference_update(set2)
>>> set1
{1, 2}
discard() set1.discard(elem) Delete elem element of set1 >>> set1 = {1,2,3}
>>> set1.discard(2)
>>> set1
{1, 3}
>>> set1.discard(4)
{1, 3}
intersection() set3 = set1.intersection(set2) 取 set1 和 set2 的交集给 set3 >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set3 = set1.intersection(set2)
>>> set3
{3}
intersection_update() set1.intersection_update(set2) 取 set1和 set2 的交集,并更新给 set1 >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set1.intersection_update(set2)
>>> set1
{3}
isdisjoint() set1.isdisjoint(set2) 判断 set1 和 set2 是否没有交集,有交集返回 False;没有交集返回 True >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set1.isdisjoint(set2)
False
issubset() set1.issubset(set2) 判断 set1 是否是 set2 的子集 >>> set1 = {1,2,3}
>>> set2 = {1,2}
>>> set1.issubset(set2)
False
issuperset() set1.issuperset(set2) 判断 set2 是否是 set1 的子集 >>> set1 = {1,2,3}
>>> set2 = {1,2}
>>> set1.issuperset(set2)
True
pop() a = set1.pop() 取 set1 中一个元素,并赋值给 a >>> set1 = {1,2,3}
>>> a = set1.pop()
>>> set1
{2,3}
>>> a
1
remove() set1.remove(elem) 移除 set1 中的 elem 元素 >>> set1 = {1,2,3}
>>> set1.remove(2)
>>> set1
{1, 3}
>>> set1.remove(4)
Traceback (most recent call last):
  File "<pyshell#90>", line 1, in <module>
    set1.remove(4)
KeyError: 4
symmetric_difference() set3 = set1.symmetric_difference(set2) 取 set1 和 set2 中互不相同的元素,给 set3 >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set3 = set1.symmetric_difference(set2)
>>> set3
{1, 2, 4}
symmetric_difference_update() set1.symmetric_difference_update(set2) 取 set1 和 set2 中互不相同的元素,并更新给 set1 >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set1.symmetric_difference_update(set2)
>>> set1
{1, 2, 4}
union() set3 = set1.union(set2) 取 set1 和 set2 的并集,赋给 set3 >>> set1 = {1,2,3}
>>> set2 = {3,4}
>>> set3=set1.union(set2)
>>> set3
{1, 2, 3, 4}
update() set1.update(elem) 添加列表或集合中的元素到 set1 >>> set1 = {1,2,3}
>>> set1.update([3,4])
>>> set1
{1,2,3,4}

 

Python frozenset集合(set集合的不可变版本)

frozenset 是 set 的不可变版本,因此 set 集合中所有能改变集合本身的方法(如 add、remove、discard、xxx_update 等),frozenset 都不支持;set 集合中不改变集合本身的方法,fronzenset 都支持。

在交互式解释器中输入 dir(frozenset) 命令来查看 frozenset 集合的全部方法,可以看到如下输出结果:

 

>>> dir(frozenset)
['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
>>> 

很明显,frozenset 的这些方法和 set 集合同名方法的功能完全相同。

frozenset 的作用主要有两点:

    1. 当集合元素不需要改变时,使用 frozenset 代替 set 更安全。
    2. 当某些 API 需要不可变对象时,必须用 frozenset 代替set。比如 dict 的 key 必须是不可变对象,因此只能用 frozenset;再比如 set 本身的集合元素必须是不可变的,因此 set 不能包含 set,set 只能包含 frozenset。
[root@kube set]# cat demo2.py 
s = set()
#创建 frozenset 不可变集合,使用 frozenset() 函数
frozen_s = frozenset('Kotlin')
# 为set集合添加frozenset
s.add(frozen_s)
print('s集合的元素:', s)
sub_s = {'Python'}
# 为set集合添加普通set集合,程序报错
s.add(sub_s)
[root@kube set]# py demo2.py 
s集合的元素: {frozenset({'o', 't', 'l', 'n', 'K', 'i'})}
Traceback (most recent call last):
  File "demo2.py", line 9, in <module>
    s.add(sub_s)
TypeError: unhashable type: 'set'
[root@kube set]# 

 

 浅拷贝,指的是重新分配一块内存,创建一个新的对象,但里面的元素是原对象中各个子对象的引用。

所谓深拷贝,是指重新分配一块内存,创建一个新的对象,并且将原对象中的元素,以递归的方式,通过创建新的子对象拷贝到新对象中。因此,新对象和原对象没有任何关联。

 

 Python 中以 copy.deepcopy() 来实现对象的深度拷贝

copy这部分参考: http://c.biancheng.net/view/5358.html

 

Guess you like

Origin www.cnblogs.com/zy09/p/11599261.html