In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to use Python built-in library collections", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use Python built-in library collections" bar!
There are many useful built-in modules in Python, such as datatime, json, and so on. This article introduces the use of the collections module. When using the collections module, import the module first, as follows:
Import collections
Let's first introduce the use of the OrderedDict module. In Python3.5 (included), the dictionary is unordered, that is, it is not sorted in the order in which the user inserts it. As shown below, we find that the output is not output in the order in which the input is entered.
X = dict () # unordered dictionary x ['stock1'] = "600213" x [' stock2'] = "600223" x ['stock3'] = "600233" print (x) # {' stock1': '600213,' stock3': '600233,' stock2': '600223'}
After sorting dictionaries with operator.itemgetter, a list variable is returned, not a dictionary. If you convert this list to a dictionary, you will find that it has changed back to an unordered dictionary. As follows:
X = {"stock1": "600213", "stock2": "600223", "stock3": "600233"} sorted_x = sorted (x.items (), key=operator.itemgetter (0)) print (type (x)) # print (type (sorted_x)) # print (dict (sorted_x)) # {'stock1':' 600213, 'stock3':' 600233, 'stock2':' 600223'}
What if we want to keep the dictionary in the order in which we insert it? You can initialize the dictionary with collections.OrderedDict so that the unordered dictionary becomes an ordered dictionary, as shown below:
X = OrderedDict () x ['stock1'] = "600213" x [' stock2'] = "600223" x ['stock3'] = "600233" print (x) # OrderedDict ([(' stock1', '600213'), (' stock2', '600223'), ('stock3',' 600233')]) print (type (x)) #
The dictionary generated by OrderedDict supports the following attributes:
# values () gets all the value of the dictionary and returns a list of print (x.values ()) # odict_values ([['600213,' 600223,]) # setdefault () to get the value of the specified key, if key does not exist Then create val = x.setdefault ('stock4') print (val, x) # None OrderedDict ([(' stock1', '600213'), (' stock2', '600223'), ('stock3',' 600233'), ('stock4', None)]) # popitem () delete the last element according to the LIFO principle Return key-valueprint (x.popitem (), x) # ('stock4', None) OrderedDict ([(' stock1', '600213'), (' stock2', '600223'), ('stock3',' 600233')]) # pop () to get the value of the specified key And delete k = x.pop ('stock1') print (k, x) # 600213 OrderedDict ([(' stock2', '600223'), ('stock3'') from the dictionary '600233)) # keys () gets all the keyprint of the dictionary (x.keys ()) # clear () empties the ordered dictionary # x.clear () # copy () copy new_dic = x.copy () print (new_dic) # items (returns a list of constituent elements of key-value pairs) print (x.items ()) # fromkeys () specifies a list Take the values in the list as the key of the dictionary and generate a dictionary dic = OrderedDict () name = ['allen',' belln', 'cllen'] print (dic.fromkeys (name)) # OrderedDict ([(' allen', None), ('belln', None), (' cllen', None)]) print (dic.fromkeys (name, 20)) # OrderedDict ([('allen', 20), (' belln', 20), ('cllen', 20)])
Since Python 3.6.The underlying dictionary mechanism of Python has been changed to an ordered dictionary. Although the use value of collections.OrderedDict has been reduced, defaultdict in collections is still useful to implement an one-key, multi-valued dictionary, as follows:
Y = defaultdict (list) # one-button multi-value dictionary uses defaultdicty ["stock"] .append ("600213") y ["stock"] .append ("600223") y ["stock"] .append ("600413") y ["stock"] .append ("600513") y ["stock"] .append ("600225") y ["stock"] .append ("600273") print (y) # defaultdict (, {'stock': [' 600213,' 600223,600413,600513') '600225,' 600273]})
Next, we will introduce Counter in collections. Counter is a simple counter designed to track the number of occurrences of a value. Counter stores the number of times values appear in dictionary key-value pairs, as shown below:
C_dict = Counter ('yyydadyyyaadadsaaaxxxx') print (c_dict) # Counter ({'aqu: 7,' Yee: 6, 'Dai: 4,' x: 4,'s cargo: 1})
Of course, you can also use the for loop to track the number of times the value appears, as shown below, but it is more efficient to use Counter.
Data = 'yyydadyyyaadadsaaaxxxx'val_cnt = {} for i in data: i_cnt = val_cnt.get (iP0) # the value of the lookup key val_ CNT [I] = i_cnt + 1print (val_cnt) # {' yellows: 6, 'dice: 4,' axiom: 7, 'Xerox: 4} print (val_cnt.get (' a')) # 7
Finally, let's introduce ChainMap, which can speed up the merging of dictionaries. Usually the way we merge dictionaries is as follows:
Dicta = {I: I + 1 for i in range (1,100,2)} dictb = {I: I + 2 for i in range (1,100,2)} dictc = {I: I + 3 for i in range (1,100,2)} dictd = {I: I + 4 for i in range (1,100,2)} dic_total = dicta.copy () dic_total.update (dictb) dic_total.update (dictc) dic_total.update (dictd) print (dic_total) print (dic_total.get (3,0))
Use a more efficient ChainMap method, as follows:
Dic_total = ChainMap (dicta, dictb, dictc, dictd) Thank you for reading, the above is the content of "how to use Python built-in library collections". After the study of this article, I believe you have a deeper understanding of how to use Python built-in library collections, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.