Python's Path to growth second (4) _collections series

Source: Internet
Author: User
Tags iterable

First, to remove the number greater than 66 and less than 66 of the number

Small exercise: Requirements There is a list of lists with a set of numbers that require numbers greater than 66 and numbers less than 66 to be removed separately

 AA = [11,22,33,44,55,66,77,88,99,90] 
dic = {}
for I in AA:
&nbs p;   ifi <=:
        if ' K1 ' in Dic.keys ():
  & nbsp;         dic[' K1 '].append (i)
         else:
            # Creates a list of only one element
          
dic[' k1 ' = [i,]   #为了规范请使用逗号
    Else:
        if ' K2 ' in Dic.keys ():
             dic[' K2 '].append (i)
         Else:
            dic[' k2 '] = [I,]

Print ( dic[' K1 ')
Print (dic[' K2 ')
#k1和k2就分别保存了大于66和小于66的结果

Second, Collections series
(1) Counter counter

Counter is a supplement to the dictionary type that is used to track the number of occurrences of a value.

PS: With all the functions of the Dictionary + own function

Example:
Import Collections
F1 = collections. Counter (' ASDWQEWQDSADSADSA ')
Print (F1)
Results:
Counter ({' A ': 4, ' d ': 4, ' s ': 4, ' Q ': 2, ' W ': 2, ' E ': 1})
#这个例子就是统计出元素出现的次数

(2) Ordered dictionary class ordereddict (dict):

Orderddict is a supplement to the dictionary type, and he remembers the order in which the dictionary elements were added, thus making the dictionary more orderly

Example:

Import Collections
F1 = collections. Ordereddict ()
F1["a"] = 3
F1["C"] = 2
F1["B"] = 1
F2 = {}
F2["a"] = 3
F2["C"] = 2
F2["B"] = 1
Print (F1,F2)

Results: ordereddict (' A ', 3), (' C ', 2), (' B ', 1)]) {' B ': 1, ' C ': 2, ' A ': 3}

From the above can be found that the dictionary with the same value to use ordereddict in order to sort by adding

Internal mechanism:

In the normal dictionary F2 such a sort:

F2 = {' B ': 1, ' C ': 2, ' A ': 3}

After using ordereddict, he generates a list to save the order in which the dictionary is added.

F1 = {' B ': 1, ' C ': 2, ' A ': 3}

F1_list = ["A", "C", "B"]

This allows you to get an ordered dictionary through a for loop

Don't be serious, huh?


(3) Default dictionary (defaultdict)

Defaultdict is a supplement to the type of dictionary, which defaults to a type for the value of the dictionary.

Import Collections
F1 = collections.defaultdict (list)
F1["A"].append (1)
Print (F1)
The above effect is equal to the following, so defaultidict is set value to default to list type
F1 = {}
F1["a"] = []
F1["A"].append (1)
(4) can be named tuple namedtuple

That is, the value of the first name, and then pass the value, mainly for the plan to think of the X, Y axis

Import Collections

Atuple = Collections.namedtuple ("Atuple", [' X ', ' y ', ' z '])
New = Atuple (A.)
Print (new)
Atuple (X=1, y=2, z=3)
(5) Bidirectional queue Collections.deque

Two-way teams are listed, for example, with a list that can fetch data from the left and right, as well as add data from the left and right.

Method:

(1) def append (self, *args, **kwargs): Add right
# Real Signature Unknown
"" "Add an element to the right side of the Dequ '" ""
Pass
(2) def appendleft (self, *args, **kwargs): Add to the left of the queue
# Real Signature Unknown
"" "Add an element to the left side of the deque." "" "
Pass
(3) Clear (Self, *args, **kwargs): Clear
Real signature Unknown
"Remove all elements from the deque." "" "
The

(4) F count (self, value): The number of elements that appear
Real signature unknown; Restored from __doc__
"" "D.count (value), integer--return number of occurrences of value" ""
0
(5) def extend (self, *args, **kwargs): Expand Right Add
# Real Signature Unknown
"" Extend the right side of the deque with elements from the iterable "" "
Pass
(6) def extendleft (self, *args, **kwargs): Extended left Add
# Real Signature Unknown
"" "Extend the left side of the deque with elements from the iterable" ""
Pass
(7) def pop (self, *args, **kwargs): remove element from right
# Real Signature Unknown
"" "Remove and return the rightmost element." "
Pass
(8) def popleft (self, *args, **kwargs): remove element from left
Real signature Unknown
"" "Remove and return the leftmost element." "
Pass
(9) def remove (self, value): Deletes the specified element
# Real Signature Unknown; Restored from __doc__
"" "D.remove (value)--Remove first occurrence of value." ""
Pass
def reverse (self): Flip
# Real Signature Unknown; Restored from __doc__
"" "D.reverse ()--Reverse *in place*" ""
Pass
Three, one-way queue
Q =queue.queue (10) Creates a one-way queue, in parentheses, the number of elements that can be placed in the queue
Q Put add element
Q Get remove Element
  • Characteristics of the queue: Who goes first, who goes first?
  • Stack features: Clip structure, plus first out

Python's Path to growth second (4) _collections series

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.