Python--collections

Source: Internet
Author: User
Tags ming pop value

Namedtuple

From collections Import Namedtuplegirl = Namedtuple ("AAA", ["Name", "Age", "gender", "anime"]) girl = Girl (name= "Satori", a Ge=18, gender= "F", Anime= "Orient Spirit Hall") print (Girl)  # aaa (name= ' Satori ', age=18, gender= ' f ', anime= ' Oriental Spirit Hall ') print ( Girl.name)  # satoriprint (girl.age)  # 18print (girl.anime)  # Oriental Spirit Hall

  

From collections Import Namedtuplegirl = Namedtuple ("AAA", ["Name", "Age", "gender", "anime"]) T = ("satori", +, "F", "Orient Temple ") # can also not specify the column name, directly in order to pass in the Parameters girl = Girl (*t) print (girl)  # aaa (name= ' Satori ', age=18, gender= ' f ', anime= ' Oriental Spirit Hall ') # You can also pass in a dictionary d = {    "name": "Satori", "Age": "    Gender": "    F",    "anime": "Oriental Spirit Hall"}girl = Namedtuple ("AAA", [" Name "," Age "," gender "," anime "]) girl = Girl (**d) print (girl)  # aaa (name= ' Satori ', age=18, gender= ' f ', anime= ' Oriental Spirit House ') )

  

Defaultdict

# if it's a generic dictionary, when we want to count the number of words L = ["A", "B", "A", "C", "C", "a", "a"]d = {}for I in L: If I is not in    D:        d[i] = 1    Else :        d[i] + = 1print (d)  # {' A ': 4, ' B ': 1, ' C ': 2}# What's wrong with this piece of code? In fact, there is no problem, that is, when the amount of data is large, it will be very troublesome # this time defaultdict appeared

  

From collections import defaultdict# inside to pass in a callable object, what does that mean? Default_dict = defaultdict (int) # When I access a nonexistent value print (default_dict["A"]) # 0default_dict = defaultdict (str) print (default_ Dict["A"]) # "" Default_dict = defaultdict (tuple) print (default_dict["A"]) # () default_dict = defaultdict (list) print ( Default_dict["A"]) # []default_dict = Defaultdict (set) print (default_dict["A"]) # set () Default_dict = Defaultdict (dict) Print (default_dict["A"]) # {}# See this should be understood, if access to a nonexistent key, then the key is created first, and then value corresponds to the initial value of the incoming type in the defaultdict L = ["A", "B", "a", "C", "C", "a", "a"]default_dict = defaultdict (int) for i in L: # First No key will be created, then value is initialized to 0, then execute +=1 # Note: In the absence of the corresponding key, this line The code represents the execution of two steps # First execute default_dict[i] = 0 # and then Default_dict[i] + + 1 # When key is present, execute the +=1 operation directly default_dict[i] + = 1 # this The kind of operation is much easier than the ordinary list, you can also use SetDefault, but this simple print (default_dict) # defaultdict (<class ' int '), {' A ': 4, ' B ': 1, ' C ': 2}] Print (Type (default_dict)) # <class ' collections.defaultdict ' ># can also be converted directly to the dictionary print (Dict (default_dict) # {' A ': 4, ' B ': 1, ' C ': 2}# so defaultdict how is it implemented? The main use of __missing__ this magical function class A (dict): Def __init__ (self, **kwargs): Super (). __init__ (**kwargs) def __missing__ (Self, key): Return key# must inherit dicta = A (name= "Satori", age=19) # You can see only the name and age of the two properties print (a["name") # Satoriprint (a["Age"]) # 19# When I visit a nonexistent property print (a["MMP"]) # mmp# __missing__ The role of this, of course, this magic method can only be used in Dict sub-class. For ordinary classes, you can use __getattr__# to simulate Defaultdictclass satoridict (dict): Def __init__ (self, **kwargs): Super (). __INIT__ (* *   Kwargs) def __missing__ (self, Key): Self[key] = 0 return self[key] def __getitem__ (self, item): # Return Self[item], can not return Self[item] # Why? Because the call __getitem__,return Self[item], and then execute __getitem__, and return Self[item], so infinite recursion # So how to get the value? Return item will not error, but only the key, not the value AH # we can call the method of the parent class value = Super (). __getitem__ (item) # will execute __getitem_ first        _ Method, when executing super (). __getitem__ If there is no __missing__ method, will error, keyerror. # if there's __missIng__ then executes the __missing__ method, sets Self[key]=0, returns Self[key] return Valuesatori = Satoridict (name= "Satori", age=18, gender= "F" Print (satori["name"]) # Satoriprint (satori["Age"]) # 18# access a nonexistent value print (satori["AAA"]) # 0

  

  

Deque

# First look at Queuefrom queue import Queueq = Queue () q.put (1) q.put (2) q.put (3) print (Q.get ())  # 1print (Q.get ())  # 2print (Q.get ())  # 3# Default queue, only append, and can only be taken from the beginning

  

From collections import deque# double-ended queue, can be inserted from two segments, can also be taken from two segments q = Deque (("A", "B", "C")) Q.append (1) q.appendleft (2) print (q) # deque ([2, ' A ', ' B ', ' C ', 1]) # can also be indexed by the value print (q[1]) # a# by pop value print (Q.pop ()) # 1print (Q.popleft ()) print (q) # deque ([' A ', ' B ', ' C ']), you can see the same as list, after pop q element reduced # Deque Most of the API and list is consistent, just deque more appendleft,popleft,extendleft# on the list how to operate, Deque also how to operate on the line, will list will be deque, here are some methods do not repeat the # most important point, deque and queue is also thread-safe, is the Gil this super Lock protection # and queue compared to Deque also has an important place to import queueq1 = queue. Queue (maxsize=3) q2 = deque (maxlen=3) # When the Q1 is stuffed with three elements, try to plug the fourth one in order to # but for the Q2, it's all right, let's print it. Q2.append (1) q2.append (2) Q2.append (3) print (Q2) # deque ([1, 2, 3], maxlen=3) q2.append (4) print (Q2) # deque ([2, 3, 4], maxlen=3) q2.append (5) Print (Q2 # deque ([3, 4, 5], maxlen=3) q2.append (6) Print (Q2) # deque ([4, 5, 6], maxlen=3) # You can see a maximum of three, then add, then it will be squeezed out.  Can be used to make history, up to see how many times etc. try:q2.insert (1, "Satori") except Exception as E:print (e) # deque already at its maximum size# In addition, when full, you can not insert the value by insert # so appendleft? Let's try Q2.ap.Pendleft ("Satori") Print (Q2) # deque ([' Satori ', 4, 5], maxlen=3) # 6 No # can be seen, when inserted from behind (O (*////▽////*) q), then the front will be squeezed out # When I insert from the front (O (*////▽////*) q), the back will be squeezed out # extend? Q2.extend (["Mashiro", "Miku"]) print (Q2) # deque ([5, ' Mashiro ', ' Miku '], maxlen=3) # can be seen, Satori and 4 No, the description extend is also possible # The same extendleft can also be used, here no longer try

  

Counter

From collections import counter# in defaultdict, we counted the number of values in the list # Counter can do more convenient L = ["A", "B", "A", "C", "C", "a", "a"]c = Counter (l) print (c) # Counter ({' A ': 4, ' C ': 2, ' B ': 1}) # and the result is a direct statistic # and the Counter object is a subclass of Dict, explaining that the api,counter of the dictionary can also use print (c[" A "]) # 4# can of course also be translated into the dictionary print (Dict (c)) # {' A ': 4, ' B ': 1, ' C ': 2}# is not only a list, as long as it is possible to iterate the object is ok s =" AAAABBBCCD "C2 = Counter (s) print (C2) # Counter ({' A ': 4, ' B ': 3, ' C ': 2, ' d ': 1}) # above also said, Counter is a subclass of Dict # then Counter can also use the Update method, and more powerful c2.update ("ABCD") p Rint (C2) # Counter ({' A ': 5, ' B ': 4, ' C ': 3, ' d ': 2}) # You can see that the ABCD and the s above are a combined statistic # you think strong is strong here? C2.update (["A", "B", "C", "D", "Gu Ming Basin"]) print (C2) # Counter ({' A ': 6, ' B ': 5, ' C ': 4, ' d ': 3, ' Old Ming Basin ': 1}) # I can update a list, that The elements in the list will act as an overall statistic for the (ancient Ming Basin) # also update can accept a Counterc3 = Counter ("aaaaaaaaaaa") Print (C3) # Counter ({' A ': one}) C2.update (C3 Print (C2) # Counter ({' A ': +, ' B ': 5, ' C ': 4, ' d ': 3, ' Old Ming Basin ': 1}) # There's one more important way # What if we want to select the three key with the largest value in the C2? # Direct implementation will be cumbersome, can use HEAPQ, of course counter is also called Heapqimport Heapqprint (heapq.nlarGest (3, C2, Key=lambda x:c2[x]) # [' A ', ' B ', ' C ']# take a look at Counterprint (C2.most_common (3)) # [(' A ', ' +], (' B ', 5), (' C ', 4 ]# will display the largest value of the key, and key corresponding to the list of nested tuples in order, very intuitive # you think Counter is over, and it's really enough for now # but there are some black tech print (C2) # Counter ({' A ': +, ' B ': 5, ' C ': 4, ' d ': 3, ' Old Ming Basin ': 1} ' Print (C3) # Counter ({' A ': one}) ' Print (C2 + C3) # Counter ({' A ': ', ' B ': 5, ' C ': 4, ' d ': 3, ' The Old Ming Basin ': 1} # C2 + C3, which means the combination of the results of the two, the same key, then add the corresponding value print (C2-C3) #Counter ({' A ': 6, ' B ': 5, ' C ': 4, ' d ': 3, ' Guming Basin ': 1}) # C2-C3, indicating that if there is C2 element in the C3, the element is subtracted from the C2, and of course there is a number of questions # So, does counter support the operation of the collection? Like &|^ et cetera # let's see C4 = Counter ("AABBBCC") C5 = Counter ("BBCCDD") print (C4) # Counter ({' B ': 3, ' a ': 2, ' C ': 2}) print (C5) # Counter ({' B ': 2, ' C ': 2, ' d ': 2}) # C4 & c5, unlike C4 + c5, which is really doing the intersection, does not add # and key is the same, select the value of the small one print (C4 & c5) # Count ER ({' B ': 2, ' C ': 2}) # key is the same, it does not add value, but instead selects the larger one print (C4 | c5) # Counter ({' B ': 3, ' a ': 2, ' C ': 2, ' d ': 2}) ' Print (c4 ^ c5), counter does not support ^ (that is, the symmetry of the difference set) of the operation, there is no meaning ' ' ' # above is I can think of the counter of the whole content, perhapsThere are some ways not to introduce # but you will be the dictionary of those methods, but also certainly will be counter of those methods # counter the most important concept and usage of this place, personally think that should be enough 

  

Ordereddict

From collections import ordereddict# know is a sequential dict# inherited from Dict, so Dict has the API, it has d = ordereddict () d["a"] = 1d["E"] = 2d[" C "] = 3print (d)  # ordereddict ([' A ', 1), (' E ', ' 2 '), (' C ', 3)]) # Obviously the same as the order we add # In addition to introducing a api,move_to_endd.move_to_end ( "A")  # from the name can also be understood, the move a to the last print (d)  # ordereddict ([' E ', 2), (' C ', 3), (' A ', 1)]) # Other and dictionary similar, not introduced.

  

Chainmap

From collections Import CHAINMAPD1 = {"A": 1, "B": 2}d2 = {"C": 2, "D": 2}d = Chainmap (d1, D2) for K, V in D.items ():    p Rint (k, V) ' C 2d 2a 1b 2 ' # So Chainmap's role is to combine multiple dictionaries into a single dictionary # What happens if you have multiple dictionaries and keys coincide? D3 = {"A": 1, "B": 2}d4 = {"B": 3, "C": 4}d = Chainmap (D3, D4) for K, V in D.items ():    print (k, v) ' A 1b 2c 4 "# can be seen even though Value is different, or only the first # of this method is compared like chainfrom itertools import Chaina = [1, 2, 3]b = "abc" c = {1, 2, 3}d = {"Name": "Satori", "age" : 15}for I in Chain (a, B, C, D):    print (i) ' 123abc123nameage '

  

Python--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.