Tenth lesson: Re-discussion of data structure and type

Source: Internet
Author: User
Tags iterable

One, list, dict, tuple they are actually good base friends

1. There is no best data structure, only the most applicable.

2. Understand each data structure to ingenious

3. They transform each other so easily

PS: If a problem can be solved with Python's built-in data type, it is recommended to use the built-in data type, which is more efficient.

list[1,2,3,4] is orderly.

LIST[0]

LIST[1]

LIST[2]

If the issues involved are sequential, consider using list

The dictionary is the key value (essentially the list is also the key value, the key is the cursor, but the integer type), but the dictionary key can be a string (more semantic, which in reality there are many scenes, such as students all the results of the course), can also be a tuple.

Tuples and List conversions

    A = [1,2,3,4]    = list (a)    = tuple (a)

To turn list into a dictionary, list needs to satisfy a certain format

    A = [(1,3), (2,4)]    = Dict (a)

This method is more commonly used. In the process of actually processing the data, we can encounter a variety of situations, it is important to transform the data structure and use the appropriate method to process the original data.

Second, "Derivation" (list deduction) re-discussion

The performance of the derivation is very little, we need to use it more. Let's look at the nature of the list derivation.

    #Coding=utf-8    """[0,1,2,3,4,5,6,7,8,.....,]"""x= [x forXinchXrange (101)]    Printx"""To disassemble, from outside to inside, from left to right part one [] second part X third part for X in Xrange (101)"""new_list= []     forXinchXrange (101): New_list.append (x)Printnew_list"""

Third, sort

1. Sorted

There are two ways to view the help document for an integral type, as follows (1) help (int) help (sorted)>>>Help (sorted)-On built-inchfunction sortedinchModule__builtin__: Sorted (...) Sorted (iterable, CMP=none, Key=none, Reverse=false)--new sorted list iterable: Required parameter, fill in an iterator object reverse: reverse, reverse>>> a = [1,2,3,4]    >>> Sorted (a,reverse=True) [4, 3, 2, 1]    >>>A [1, 2, 3, 4Note: Sorted is not changed in place and needs to be assigned.     This is not the same as the sort method. >>>Help (A.sort)-On built-inchfunction Sort:sort (...) L.sort (CMP=none, Key=none, Reverse=false)--Stable sort *in place*; CMP (x, y)--1, 0, 1the sort and sorted parameters are the same. >>> a = [1,2,3,4]    >>> A.sort (reverse =True)>>>A [4, 3, 2, 1Note: Sort in-place modify a, the sorted is different, and the two methods used are not the same. Sorted (A, reverse=true) A.sort (reverse=true) sorted is essentially a function for an iterative object, and sort is a built-in method for an iterative object.

2. List's Sort method

2.1 Key is best used

What is 2.2 cmp (A>B)-(A<B)

Let's talk about key optional parameters: key is to manipulate the elements in the list, and to sort the results of the operation.

A = ['12323','2343443',' About'] A.sort (Key=int)#sort characters in numeric forma= [('a', 2), ('C', 4), ('b', 3)] A.sort (Key=LambdaX:x[1]) A.sort (Key=LambdaX:X[1], reverse =True) CMP (2, 1) = = (2>1)-(2<1) = = 1-0 = = 1CMP (1, 3) = = (1>3)-(1<3) = = 0-1 = = 1CMP (2,2) = = (2>2)-(2<2) = = 0-0 = =0 cmp (A, B) returns three values, a>b returns 1, A&LT;B returns-1, a=B returns 0 CMP has been deprecated in python3 and has a poor performance.

3. What about multilevel sequencing?

    >>> a = [(5,6,3), (3,6,9), (1,7,5)]    import  operator     >>> A.sort ( Key=operator.itemgetter (+))    >>> a    [(5, 6, 3), (3, 6, 9), (1, 7, 5)]  #     

4. How dictionaries are sorted

As a job, you can study it yourself.

Four, string template application

1. Recall, what are the different ways of string templates?

    '%s is a%s'% ('He',' Boy')    '% (WHO) s is a% (gender) s'% Dict (who ='He', gender =' Boy')    '% (WHO) s is a% (gender) s'% {'W.H.O.':'He','Gender':' Boy'}    '{who} is a {gender}'. Format (who ='He', gender =' Boy')    '{} is a {}'. Format ('He',' Boy')

2. Typical application 1:html template

    http://news.163.com/16/0529/01/bo6s19k100014aed.html    > Press Center > Scrolling news > Body    Ecust two students lost their mentors to participate in the factory (    figure)2016-05-29 01:47:34 Source: Beijing News (Peking)    http://news.163.com/16/0528/19/  bo651sag000146be.html    > News Center > Scrolling news > Text    Prime Minister push "put on the Tube" The State Department    is prepared to do so 2016-05-28 19:09:36 Source: China News Network (Beijing)    

3. More important than strong targeting

    We recommend using the. format format, but also according to the actual situation, when the database is a key-value pair, it may be better to use the placeholder + dictionary form.

One, list, dict, tuple they are actually good base friends 1.     There is no best data structure, only the most applicable. 2. Understand each data structure to ingenious 3. They transform each other so easily.

PS: If a problem can be solved with Python's built-in data type, it is recommended to use the built-in data type, which is more efficient.
list[1,2,3,4] is ordered List[0] list[1] list[2]
If the problem is in order, you can consider using the list dictionary is a key value (in essence, the list is also the key value, the key is the cursor, but the integer), but the dictionary key can be a string (more semantic, which in reality there are many scenes, such as students all the results of the course), can also be a tuple.
Tuples and List conversions
A = [1,2,3,4] A = List (a) a = tuple (a)
To turn list into a dictionary, list needs to satisfy a certain format a = [(1,3), (2,4)] A = Dict (a)
This method is more commonly used. In the process of actually processing the data, we can encounter a variety of situations, it is important to transform the data structure and use the appropriate method to process the original data.



Second, "Derivation" (list deduction) again the performance of the deduction is very little, we have to use more. Let's look at the nature of the list derivation.
# Coding=utf-8
"" "[0,1,2,3,4,5,6,7,8,....., 100]
"""
x = [x for x in xrange (101)]print X
"" "for disassembly, from outside to inside, from left to right first part [] second part X third part for X in xrange (101)" ""
New_list = []for x in Xrange (101): New_list.append (x)
Print New_list
"""

Third, sort 1. Sorted
c There are two ways to view the Help document for an integer type, as shown in Assist (1) (int)
Help (sorted)
>>> Help (sorted) to built-in function sorted in module __builtin__:
Sorted (...) Sorted (iterable, Cmp=none, Key=none, Reverse=false)--New sorted list
Iterable: Required parameter, fill in an iterator object reverse: Reverse, Reverse


>>> a = [1,2,3,4]>>> sorted (a,reverse=true) [4, 3, 2, 1]>>> a[1, 2, 3, 4]
Note: Sorted is not changed in place and needs to be assigned. This is not the same as the sort method.
>>> Help (A.sort)-on built-in function sort:
Sort (...)    L.sort (Cmp=none, Key=none, Reverse=false)-stable sort *in place*; CMP (x, y)-1, 0, 1
The sort and sorted parameters are the same.
>>> a = [1,2,3,4]>>> a.sort (reverse = True) >>> a[4, 3, 2, 1]
Note: Sort a in-place, this sorted is different, and the two methods used are not the same. Sorted (A, reverse=true) A.sort (reverse=true) sorted is essentially a function for an iterative object, while sort is a built-in method for an iterative object.

2. List Sort method 2.1 key best with 2.2 CMP is what (a>b)-(A&LT;B)


Let's talk about key optional parameters: key is to manipulate the elements in the list, and to sort the results of the operation.
A = [' 12323 ', ' 2343443 ', ']a.sort ' (key=int) # sort characters in numbers

A = [(' A ', 2), (' C ', 4), (' B ', 3)]a.sort (key = Lambda x:x[1]) a.sort (key = lambda x:x[1], reverse = True)

CMP (2,1) = = (2>1)-(2<1) = = 1-0 = 1 cmp (1,3) = = (1>3)-(1<3) = = 0-1 =-1 cmp (2,2) = = (2>2)- (2<2) = = 0-0 = = 0
CMP (A, B) returns three values, A&GT;B returns 1, A&LT;B returns-1, A=B returns 0
CMP has been abandoned in Python3, and its performance is not good.

3. What about multilevel sequencing?
>>> a = [(5,6,3), (3,6,9), (1,7,5)]>>> import operator >>> A.sort (Key=operator.itemgetter ( ) >>> a[(5, 6, 3), (3, 6, 9), (1, 7, 5)] # After sorting according to Cursor 1, sort according to Cursor 2.
The module operator can be researched on its own.

4. How the dictionary is sorted as a job can be researched by itself.


Four, the string template application 1. Recall, what are the different ways of string templates?


'%s is a%s ' percent (' he ', ' boy ') '% (WHO) s is a% (gender) s '% of dict (who = ' he ', gender = ' boy ') '% (WHO) s are a% (gender) s '% {' Who ': ' He ', ' gender ': ' Boy '}
' {who} was a {gender} '. Format (who = ' he ', gender = ' boy ') ' {} was a {} '. Format (' He ', ' boy ')


2. Typical application 1:html template
http://news.163.com/16/0529/01/BO6S19K100014AED.html NetEase Home > News Center > Scrolling news > Body ecust two students ' loss of life tutor participation in the factory (figure) 2016-05-29 01:47:34 Source: Beijing News (Peking)
http://news.163.com/16/0528/19/BO651SAG000146BE.html NetEase Home > News Center > Scrolling News > Text Prime Minister push "put on the Tube" The State Department is prepared to do so 2016-05-28 19:09:36 Source: China News Network (Beijing)
The entire Web page is made of templates, leaving placeholders to dynamically fill in the contents of the request.


3. More important than strength we recommend using the. format format, but also according to the actual situation, when the database is a key-value pair, it may be better to pass in the placeholder + dictionary form.

Tenth lesson: Re-discussion of data structure and type

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.