Python learning-collections series, pythoncollections

Source: Internet
Author: User

Python learning-collections series, pythoncollections

I. counter (counter) 

Counter is a supplement to the dictionary type and is used to track the number of occurrences. ps: it has all the functions of the dictionary + its own functions.

Example:
>>> From collections import Counter
>>> C = Counter ('adsassdsdads ')
>>> Print (c)
Counter ({'A': 4, 'D': 4, 's': 5 })

Basic operation method:
>>> C = Counter ('abcdeabcdabcaba ')

1. The number of most_common (N) is sorted in ascending order to obtain the first N elements.
>>> C. most_common (3)
[('A', 5), ('B', 4), ('C', 3)]

2. sorted () lists and sorts all different elements.
>>> Sorted (c)
>>> ['A', 'B', 'C', 'D', 'E']

3. convert to a string
>>> ''. Join (sorted (c. elements ()))
'Aaaaabbbbcccdd'

4. Obtain the number of element repetitions
>>> C ['a']
5

5. Update and add element repetition times
>>> For elem in 'shazam ':
C [elem] + = 1 # increase the number of times of each element by 1
>>> C ['a']
7
>>> Print (c)
Counter ({'A': 7, 'B': 4, 'C': 3, 'D': 2, 's': 1, 'H': 1, 'Z': 1, 'M': 1, 'E': 1 })

6. update (): update the counter, which is actually an increase. If not, it is created. If yes, it is added.
>>> D = Counter ('simsalabim ')
>>> C. update (d)
>>> C ['a']
9
>>> Print (c)
Countr ({'A': 9, 'B': 5, 's': 3, 'C': 3, 'M': 3, 'I': 2, 'D': 2, 'H': 1, 'L': 1, 'z': 1, 'E': 1 })

7. Clear the dictionary
>>> C. clear ()
>>> C
Counter ()

8. elements () gets all elements in the counter. Note: not all element sets, but the iterator containing all element sets.
>>> C = Counter ('abcabc ')
>>> Sorted (c. elements ())
['A', 'A', 'B', 'B', 'C', 'C']

9. subtract () subtraction, the number of each element in the original counter minus the number of added elements
>>> C = Counter ('which ')
>>> Print (c)
Counter ({'H': 2, 'C': 1, 'w': '1', 'I': 1 })
>>> C. subtract ('Watch ')
>>> C ['H']
1
>>> C ['W']
0
>>> Print (c)
Counter ({'H': 1, 'I': 1, 'w': 0, 'C': 0, 't':-1, 'A ': -1 })

2. orderedDict)
OrderdDict is a supplement to the dictionary type. It remembers the order in which dictionary elements are added.

>>> From collections import OrderedDict
>>> Dic = OrderedDict ()
>>> Dic ['k1 '] = 'v1'
>>> Dic ['k2'] = 'v2'
>>> Dic ['k3'] = 'v3'
>>> Print (dic)
OrderedDict ([('k1 ', 'v1'), ('k2', 'v2'), ('k3 ', 'v3')])

Basic operation method:

1. Get all keys of the dictionary
>>> Dic. keys ()

2. Retrieve all dictionary values
>>> Dic. values ()

3. The items () method returns a list of (Key, value) tuples that can be traversed.
>>> Dic. items ()
Odict_items ([('k1 ', 'v1'), ('k2', 'v2'), ('k3 ', 'v3')])

4. the pop () method deletes the specified key value.
>>> Dic. pop ('k1 ')
'V1'
>>> Print (dic)
OrderedDict ([('k2', 'v2'), ('k3 ', 'v3')])

5. popitem () method. The last element of the dictionary is deleted by default.
>>> Dic. popitem ()
('K3 ', 'v3 ')
>>> Print (dic)
Odict_items ([('k1 ', 'v1'), ('k2', 'v2')])

6. The move_to_end ('k') method will specify the key value as the last
>>> Dic. move_to_end ('k1 ')
>>> Print (dic)
OrderedDict ([('k2', 'v2'), ('k3 ', 'v3'), ('k1 ', 'v1')])

7. update () update the dictionary
>>> Dic. update ({'k1': 'v111111', 'k10': 'v10 '})
>>> Print (dic)
OrderedDict ([('k1 ', 'v1111'), ('k2', 'v2'), ('k3', 'v3 '), ('k10 ', 'v10')])

3. The default dictionary defaultdict is a supplement to the dictionary type, which sets a type for the dictionary value by default.

Example:
Set [,], save all values greater than 66 to the first key of the dictionary, and save values smaller than 66 to the value of the second key.
That is: {'k1 ': greater than 66, 'k2': less than 66}
Native dictionary solution:
 1 values = [11, 22, 33,44,55,66,77,88,99]  2 my_dict = {}  3 for value in  values:      4   if value>66:          5     if my_dict.has_key('k1'):              6       my_dict['k1'].append(value)          7     else:              8       my_dict['k1'] = [value]      9   else:         10     if my_dict.has_key('k2'):             11       my_dict['k2'].append(value)         12     else:             13       my_dict['k2'] = [value]

 


Default dictionary solution:
1 from collections import defaultdict 2 values = [11, 22, 33,44, 55,66, 77,88, 99] 3 my_dict = defaultdict (list) # By default, the dictionary is set to list type 4 for value in values: 5 if value> 66: 6 my_dict ['k1']. append (value) 7 else: 8 my_dict ['k2']. append (value)

 


4. namedtuple)
Based on nametuple, you can create a type that contains all tuple functions and other functions.

From collections import namedtuple # create (name the ancestor)
>>> Mytuple = namedtuple ('myuple', ['x', 'y', 'z'])
>>> Obj = Mytuple (11,22, 33) # use x, y, and z to obtain the value of the ancestor.
>>> Obj. x 11
>>> Obj. y 22
>>> Obj. z 33

5. Two-way Queue (deque)
A thread-safe two-way queue

From collections import deque # create a bidirectional queue
>>> D = deque ()
>>> D. append ('1 ')
>>> D. append ('2 ')

1. append () insert data to the queue (insert from the right)
>>> D. append ('3 ')
>>> Print (d)
Deque (['1', '2', '3'])

2. appendleft () insert data to the queue (insert from left)
>>> D. appendleft ('4 ')
>>> Print (d)
Deque (['4', '1', '2', '3'])

3. clear () clear the queue
>>> D. clear ()
>>> Print (d)
Deque ([])

4. count () count
>>> D. append ('1 ')
>>> Print (d)
Deque (['1', '2', '1'])
>>> D. count ('1 ')
2

5. Add additional elements to the queue from the right side of extend ()
>>> D. extend (['qq', 'ww ', 'ee'])
>>> Print (d)
Deque (['1', '2', 'qq', 'ww ', 'ee'])

6. extendleft () add elements to the queue from the left
>>> D. extendleft (['qq', 'ww ', 'ee'])
>>> Print (d)
Deque (['qq', 'ww ', 'ee', '1', '2'])

7. index () to obtain the element subscript
>>> D. index ('1 ')
0

8. insert (): insert an element at a specified position
>>> D. insert (1, 'nn ')
>>> Print (d)
Deque (['1', 'nn ', '2'])

9. remove an element from the right side of pop ().
>>> D. pop ()
2
>>> Print (d)
Deque (['1', 'nn '])

10. remove an element from the left side of popleft ().
>>> D. popleft ()
1
>>> Print (d)
Deque (['nn '])

11. remove () remove the specified Element
>>> D. remove ('1 ')
>>> Print (d)
Deque (['2'])

12. reverse () reverse queue
>>> Print (d)
Deque (['1', '2'])
>>> D. reverse ()
>>> Print (d)
Deque (['2', '1'])

13. rotate () Move the number of elements specified on the right to the left of the queue
>>> D. append ('4 ')
>>> D. append ('5 ')
>>> D. append ('6 ')
>>> Print (d)
Deque (['1', '2', '3', '4', '5', '6'])
>>> D. rotate (3)
>>> Print (d)
Deque (['4', '5', '6', '1', '2', '3'])

6. One-way Queue (FIFO)
Import queue # create a one-way queue
>>> Q = queue. Queue ()

1. Add Elements
>>> Q. put ('11 ')
>>> Q. put ('22 ')

2. qsize () gets the number of elements in the queue
>>> Q. qsize ()
2

3. get () to obtain elements (first-in-first-out)
>>> Q. get ()
11
>>> Q. get ()
22

Related Article

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.