Python's Set and collections

Source: Internet
Author: User

A. Set set
Set is a set of unordered and non-repeating elements, with basic functionality including relationship testing and de-duplication elements. The collection object also supports mathematical operations such as Union (union), intersection (intersection), Difference (poor), Sysmmetric difference (symmetric difference sets).
Advantages: Fast access, native solves the problem of repetition
The set has a feature similar to dict: it can be defined with the {} curly braces, where the element has no sequence, that is, data of a non-sequential type, and the elements in the set are not repeatable, which is similar to the Dict key.
Set also has inherited a little list of features: If you can modify it in situ
Example:
>>> S1 = set ("LKAJDSFD") establishes a set
>>> s = set ([' H ', ' A ', ' B ') Here you can include a list in a collection
>>> x, y view multiple set
(Set ([' A ', ' P ', ' s ', ' M ']), set ([' A ', ' h ', ' m '])
>>> S1
Set ([' A ', ' d ', ' f ', ' K ', ' j ', ' l ', ' s '])
>>> s2 = set ([123, ' Goolge ', ' face ', ' book ', ' Face '])
>>> S2
Set ([' Book ', 123, ' goolge ', ' face '])
>>> S1
Set ([' A ', ' d ', ' f ', ' K ', ' j ', ' l ', ' s '])
>>> s3 = {"Alsdjkfa", "123"} Another way to set up a set, when there is only a key, the default is to create a set
>>> S3
Set ([' 123 ', ' ALSDJKFA '])
>>> Type (S3)
<type ' Set ' >
>>> S4 = {} When {} is empty when set to int format
>>> Type (4)
<type ' int ' >
>>> S5 = {} When there is content in {}, the default setting is Dict
>>> Type (S5)
<type ' Dict ' >
Some of the built-in features of set:
1.set (), new empty Set object
2.set (iterable), new set Object
3.add
Adds an element to a collection.
Example:
>>> S1.add ("DDDSD")
>>> S1
Set ([' A ', ' d ', ' f ', ' K ', ' j ', ' l ', ' s ', ' DDDSD ')
Note: S1.add ([three-way]) This method is not possible to add, you need to S1.add ("[Three-way]") because set adds only one element is added. Only one add at a time is supported, and multiple additions are not supported at one time.
4.clear
Delete all elements in the collection (dangerous operations)
Example:
>>> S1
Set ([' A ', ' d ', ' f ', ' K ', ' j ', ' l ', ' s ', ' DDDSD ')
>>> S1.clear ()
>>> S1
Set ([])
5.copy, Shallow copy
Example:
>>> s6 = s1.copy ()
>>> S6
Set ([' Face ', 123, ' AADF ', ' book ', ' Goolge '])
Returns a shallow copy of S1
6.pop
Randomly gets an element from the original collection and removes the acquired element from the original set, and the output of this element can be given to a variable. If empty, Keyerror is thrown
Example:
>>> s2 = set ([' Test1 ', ' test2 ', ' test3 ', ' test1 '])
>>> S2
Set ([' Test1 ', ' test3 ', ' test2 ')
>>> ret =s2.pop ()
>>> ret
' Test1 '
>>> ret =s2.pop ()
>>> ret
' Test3 '
>>> S2
Set ([' Test2 '])
>>> ret
' Test3 '
>>> ret =s2.pop ()
>>> ret
' Test2 '
>>> S2
Set ([])
7.remove
Removes an element directly from the collection if there is no reported keyerror error.
S2.remove (' test1 ')
Set ([' Test1 ', ' test3 ', ' test2 ')
>>> s2.remove (' test1 ')
>>> S2
Set ([' Test3 ', ' test2 '])
>>> s2.remove (' test1 ')
Traceback (most recent):
File "<stdin>", line 1, in <module>
Keyerror: ' Test1 '
8.discard (self, *args, **kwargs): # Real Signature Unknown
Removing an element, unlike remove, removes the return value regardless of whether it is in the collection.
Example:
>>> S2
Set ([' Test3 ', ' test2 '])
>>> s2.discard (' test1 ')
>>> s2.discard (' test2 ')
>>> S2
Set ([' Test3 '])
9.difference
Will produce a new set without changing the original collection. Take the process, loop the original elements, judge the original elements, whether in the new inside.
10.difference_update
Deletes all elements in the current set that are contained in the (new set) parameter collection, "" To update the original collection.
11.intersection
"" To take the intersection, create a new set ""
12.intersection_update
"" "to take the intersection, modify the original set" "
13.isdisjoint
"" If there is no intersection, returns True "" "
14.issubset
"" "is a Subset" ""
15.issuperset
"" "is the parent set" ""
16.symmetric_difference (self, *args, **kwargs): # Real Signature Unknown
"" "Difference set, create new Object" ""
The symmetry difference takes two different all out. will produce a new collection.
17.symmetric_difference_update (self, *args, **kwargs): # Real Signature Unknown
"" "Difference set, change the original" "" Symmetry difference to take two different all out. Update Legacy Collections
18.union (self, *args, **kwargs): # Real Signature Unknown
"" and "" "intersection
19.update (self, *args, **kwargs): # Real Signature Unknown
"" Update "" "
20.__eq__ (self, y): # Real signature unknown; Restored from __doc__
"" "X.__eq__ (y) <==> x==y" ""

Example 1:
Scenario Description: You now need to update the new (NEW_DICT) data to the old (old_dict) data.
#!/usr/bin/env python
#-*-coding:utf-8-*-
Old_dict = {
"#1": {' hostname ': ' C1 ', ' Cpu_count ': 2, ' mem_capicity ': 80},
"#2": {' hostname ': ' C2 ', ' Cpu_count ': 2, ' mem_capicity ': 80},
"#3": {' hostname ': ' C3 ', ' Cpu_count ': 2, ' mem_capicity ': 80}
}

New_dict = {
"#1": {' hostname ': ' C1 ', ' Cpu_count ': 2, ' mem_capicity ': 512},
"#3": {' hostname ': ' C3 ', ' Cpu_count ': 2, ' mem_capicity ': 1024},
"#4": {' hostname ': ' C4 ', ' Cpu_count ': 2, ' mem_capicity ': 80}
}

Import Collections #导入模块
my_dict = collections.defaultdict (list) #配置默认字典
Old_key = Old_dict.keys ()
New_key = New_dict.keys ()
Old = set (Old_key)
New = set (New_key)
Updagte_list = Set (Old.intersection (new))
Delect_list = Old.difference (updagte_list)
Delect_list = Old.difference (updagte_list)
Add_list = New.difference (updagte_list)
Updagte_add_list = Updagte_list.union (add_list)
My_dict = Old_dict
For I in Updagte_add_list:
My_dict[i] = New_dict[i]
For it1 in Delect_list:
Del My_dict[it1]
Print (my_dict)
Example 2: The difference between difference and symmetric_difference
S2 = set ([' Test1 ', ' test2 ', ' test3 ', ' test1 '])
S3 = Set ([' Test1 ', ' test2 ', ' test5 '])
Print (S2.difference (S3))
#difference S3 in the middle of the show, no matter what.
Print (S2.symmetric_difference (S3))
The result of the execution is:
Set ([' Test1 ', ' test3 ', ' test2 ')
Set ([' Test3 '])
Set ([' Test3 ', ' test5 '])
--------------------------------------------------------------------------------------------------------------- -----
Second, the collections series is a supplement to the dictionary type.
Counter counter
Ordereddict ordered Dictionary
Defaultdict Default Dictionary
Namedtuple can name a tuple

The 1.Counter counter is designed to track the number of occurrences of a value. It is an unordered container type, stored in the form of a dictionary key-value pair, where the element is counted as the key and its count as value. Inherit some of the features and functionality of the dictionary. Returns 0 instead of Keyerror when the key being accessed does not exist, otherwise returns its count.
Note: The parameters of the dictionary can also be used.
1.1 Create a counter, counter is a supplement to the dictionary type that is used to track the number of occurrences of a value.
Example:
Import Collections
Test = (' asdfasdfew ')
A =collections. Counter (Test)
Print (Type (a))
Print (a)
Execution Result:
<class ' collections. Counter ' >
Counter ({' A ': 2, ' d ': 2, ' F ': 2, ' s ': 2, ' W ': 1, ' E ': 1})
1.2 Most_common (self, n=none): All elements and counters with a quantity greater than equal n
Print (A.most_common (2))
[(' A ', 2), (' s ', 2)] #注意获得结果是随机的.
1.3 __missing__ (Self, key): For elements that do not exist, the return counter is 0
Print (a.__missing__ (' W '))
Execution Result: 0
1.4elements (self): all elements in the counter, note: This is not a collection of all elements, but rather an iterator that contains all the elements in the collection, listing all the elements in the counter.
"' Iterator over elements repeating" as many times as its count.
Example:
Import Collections
Test = (' asdfasdfew ')
A =collections. Counter (Test)
#test = collections. Counter (' Adfasdfadsfeadfasdf ')
For I in A.elements ():
Print (i)
Execution Result:
C:\Python34\python.exe e:/python/s12/day1/test1.py
D
D
F
F
A
A
W
S
S
E
1.5 Update (self, Iterable=none, **kwds): You can use one Iterable object or another counter object to update the key value. The update of the counter includes two additions and decreases.
>>> Import Collections
>>> C = Collections. Counter (' which ')
>>> c.update (' witch ') # Update with another Iterable object
>>> c[' h ']
Execution Result: 3
>>> d = Counter (' watch ')
>>> C.update (d) # Update with another counter object
>>> c[' h ']
1.6 Subtract (self, Iterable=none, **kwds): Subtract, the number of each element in the original counter minus the number of elements added after
Example:
>>> Import Collections
>>> C = Collections. Counter (' Test ')
>>> c.subtract (' text ')
>>> C
Counter ({' s ': 1, ' E ': 0, ' t ': 0, ' x ':-1})
1.7 Copy (self): "" "Copy" ""
1.8 __reduce__ (self): "" "returns a tuple (type, tuple)" "
1.9 __delitem__ (self, Elem): "" "Delete Element" ""

Example:
#items = > Process the completed value
Import Collections #导入collections模块 (counter module in collections)
obj = collections. Counter (' ASDFLKJASDLKFJAKDSJFASDJFD ')
Print (obj)
ret = Obj.most_common (4) #拿到前四位
Print (ret)
For k,v in Obj.items ():
Print (K,V)
Execution Result:
C:\Python27\python.exe e:/python/s12/day3/s1.py
Counter ({' D ': 5, ' A ': 4, ' F ': 4, ' J ': 4, ' S ': 4, ' K ': 3, ' L ': 2})
[(' D ', 5), (' A ', 4), (' F ', 4), (' J ', 4)]
(' A ', 4)
(' D ', 5)
(' F ', 4)
(' K ', 3)
(' J ', 4)
(' L ', 2)
(' S ', 4)

2. The ordered dictionary (ordereddict) is a complement to the dictionary type, and he remembers the order in which the dictionary elements were added
Example:
Import Collections #导入模块
DIC = collections. Ordereddict () #设置dic为有序字典
#dic = Dict ()
dic[' k1 '] = ' v1 '
dic[' k2 '] = ' v2 '
dic[' K3 '] = ' K3 '
Print (DIC)
Dic.popitem () #去掉最后一个加入的
Dic.pop (' K2 ') #去除后可以复制的用
Dic.setdefault (' K3 ')
Print (DIC)
Execution Result:
C:\Python34\python.exe e:/python/s12/day1/test1.py
Ordereddict ([' K1 ', ' v1 '), (' K2 ', ' V2 '), (' K3 ', ' K3 ')])
Ordereddict ([' K1 ', ' v1 '), (' K3 ', None)])
Reprint application:
>>> d = {' Banana ': 3, ' Apple ': 4, ' pear ': 1, ' Orange ': 2}
#按key排序
>>> ordereddict (Sorted (D.items (), Key=lambda t:t[0])
Ordereddict (' Apple ', 4), (' Banana ', 3), (' Orange ', 2), (' Pear ', 1)])
#按value排序
>>> ordereddict (Sorted (D.items (), Key=lambda t:t[1])
Ordereddict (' pear ', 1), (' Orange ', 2), (' Banana ', 3), (' Apple ', 4)])
#按key的长度排序
>>> ordereddict (Sorted (D.items (), Key=lambda T:len (t[0)))
Ordereddict (' pear ', 1), (' Apple ', 4), (' Orange ', 2), (' Banana ', 3)
3. The default dictionary (defaultdict) is a supplement to the type of the dictionary, which defaults to a type for the dictionary value.
Import Collections
DIC = collections.defaultdict (list)
In the dictionary by default, if the value is empty can not be added directly using parameters such as append, need to be created before you can add, and the default dictionary solves this feature.
Example:
1). Without using the default dictionary
values = [11, 22, 33,44,55,66,77,88,99,90]
My_dict = {}
For value in values:
If value>66:
If ' K1 ' in My_dict.keys ():
my_dict[' K1 '].append (value)
Else
my_dict[' k1 ' = [value]
Print (my_dict)
Else
If ' K2 ' in My_dict.keys ():
my_dict[' K2 '].append (value)
Else
my_dict[' k2 ' = [value]
Print (my_dict)
2). After using defaultdict, the whole becomes this:
From collections Import Defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
my_dict = defaultdict (list)
For value in values:
If value>66:
my_dict[' K1 '].append (value)
Else
my_dict[' K2 '].append (value)
5. Can name tuples (namedtuple)
Depending on nametuple, you can create a type that contains all the functions of a tuple and other features.
The default tuple is accessed according to the index.
For example:
t = (11,22,33,44)
Default Access Method T[0] is 11
Import Collections
Mytupleclass = collections.namedtuple (' Mytupleclass ', [' X ', ' y ', ' z '])
#相对于自己自定义了一个类模块
obj = Mytupleclass (11,22,33) #一次赋值, there are several elements in the main mytuplecleass, here you need a few. Otherwise, it cannot be performed
Print (obj.x)
Print (OBJ.Y)
Print (OBJ.Z)
Execution Result:
11
22
33

6. Queue bidirectional Queue (deque), a thread-safe bidirectional queue
6.1 Bidirectional queue
To create a deque sequence:
From collections Import Deque
D = deque ()
Deque provides a list-like method of operation:
D = deque ()
D.append (' 1 ')
D.append (' 2 ')
D.append (' 3 ')
Len (d)
D[0]
D[-1]
Output Result:
1
2
3
3
' 1 '
' 3 '
POPs are used on both ends:
D = deque (' 12345 ')
Len (d)
D.popleft ()
D.pop ()
D
Output Result:
5
' 1 '
' 5 '
Deque ([' 2 ', ' 3 ', ' 4 '])
Limit the length of the deque:
D = deque (maxlen=30)
When the limit length of deque increases by more than the limit number of items, the other side of the item is automatically deleted:
D = deque (maxlen=2)
D.append (1)
D.append (2)
D
D.append (3)
D
Deque ([1, 2], maxlen=2)
Deque ([2, 3], maxlen=2)
Add items in list to deque:
D = deque ([1,2,3,4,5])
D.extendleft ([0])
D.extend ([6,7,8])
D
Output Result:
Deque ([0, 1, 2, 3, 4, 5, 6, 7, 8])

6.2 Single Queue (FIFO)
Import Queue
Queue.queue

Python's Set and collections

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.