According to Liao Xuefeng python3 tutorial----python study sixth day

Source: Internet
Author: User


Dict

Python has a built-in dictionary, Dict full dictionary, also known as map in other languages, with key-value (Key-value) storage, with extremely fast lookup speeds.

For example, suppose you want to find the corresponding score according to the name of the classmate, if you use list, you need two lists:

>>> name = [' Xiaoming ', ' xiaohong ', ' xiaolan ']>>> scores = [90,75,59]

Given a name, to find the corresponding results, it is necessary to find the corresponding position in the names, and then remove the corresponding results from scores, the longer the list, the longer the time.

If implemented with Dict, only need a "name"-"score" of the table, directly based on the name of the results, no matter how large the table, the search speed will not be slow. Write a dict in Python as follows:

>>> d = {' Xiaoming ': $, ' xiaohong ':, ' Xiaolan ':59}>>> d[' Xiaolan ']59


Why does Dict look so fast? Because the Dict implementation principle and look for the same dictionary. Suppose the dictionary contains 10,000 Chinese characters, we need to look up a word, one way is to forget the dictionary from the first page,

Until we find the word we want, this method is the way to find the element in the list, the larger the list, the slower the lookup.


The second method is to find the page number of the word in the dictionary's index table, and then turn directly to the page to find the word. No matter which word you look for, the search speed is very fast. Does not slow down as the dictionary size increases.

Dict is the second implementation, given a word, such as ' xiaoming ', dict in the internal can be directly calculated xiaoming corresponding to the ' page number ' of the storage score, that is, 90 of the number of storage

Address, which is taken out directly, so very fast.


This Key-value storage method, when put in, must be calculated according to the value of the storage location, so that the time can be obtained by key directly to the value.

The method of putting data into dict, in addition to the initialization of the specified, can be placed by key:

>>> d[' xiaosan ' = 66>>> d[' Xiaosan ']66



Since a key can only correspond to one value, the value is placed multiple times for a key, and the following values will flush the previous value out:

>>> d[' gg ']=90>>> d[' gg ']90>>> d[' gg ']=88>>> d[' GG ']88


If key does not exist, Dict will get an error:

>>> d[' ll ']traceback (most recent): File "<pyshell#11>", line 1, in <module> d[' ll ']k Eyerror: ' LL '


To avoid a key that does not exist, there are two ways to determine whether a key exists by using in:

>>> ' LL ' in Dfalse


The second is the Get method provided by Dict, if key does not exist, you can either return None or specify value yourself:

>>> d.get (' ll ') >>> D.get (' ll ', 0) 0

Note: When none is returned, the interactive command line of Python does not display the results.


To delete a key, use the Pop (key) method, and the vaule will also be removed from the dict:

>>> d.pop (' GG ') 88>>> d{' Xiaosan ': The ' Xiaohong ': $, ' xiaoming ': All, ' Xiaolan ': 59}

Note: The order of storage inside the dict is not related to the order in which key is stored.


Compared with list, Dict has the following features:

1. Find and insert the speed is very fast, will not increase with the key increase;

2. It takes a lot of memory and a lot of wasted memory.


And the list is the opposite:

1. The time to find and insert increases as the element increases;

2. Small footprint, very little wasted memory.


So Dict is a way of using space to change time.

Dict can be used in many places where high-speed lookups are needed, almost everywhere in Python code, it is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object.


Just because Dict calculates the storage location of value based on key, if each calculation of the same key results in a different result, the dict inside is completely chaotic. The algorithm for calculating position by key is called hash Algorithm (hash)


To ensure the authenticity of the hash, the object as a key cannot be changed. In Python, strings, integers, and so on are immutable, so you can be assured of being a key. The list is mutable and cannot be a key:

>>> key=[1,2,3]>>> d[key]= ' a lsit '
Traceback (most recent): File "<pyshell#18>", line 1, in <module> d[key]= ' a lsit ' Typeerror:un Hashable type: ' List '
>>> key= ($) >>> d[key]= ' A tuple ' >>> D[key] ' a tuple '
>>> d[key]= ' 1 ', ' 2 ', ' 3 ' >>> d[key[1]
Traceback (most recent): File "<pyshell#25>", line 1, in <module> d[key[1]]keyerror:2
>>> D[key] (' 1 ', ' 2 ', ' 3 ') >>> d{(1, 2, 3): (' 1 ', ' 2 ', ' 3 '), ' Xiaohong ': ", ' Xiaosan ': 90, ' xiaoming ': , ' Xiaolan ': 59}

Set

Set is similar to Dict and is a set of keys but does not store value. Because key cannot be duplicated, there is no duplicate key in set.

To create a set, you need to provide a list as the input collection:

>>> s = set ([2]) >>> s{1,, 3}



Note that the parameter passed in [1, 2, 3] is a list, and the display {1, 2, 3} only tells you that the set has 3 elements, the order of the display does not indicate that the set is ordered.

Repeating elements are automatically filtered in set:

>>> s = set ([1,1,2,2,3,3]) >>> s{1, 2, 3}


You can add elements to the set by using the Add (key) method, and you can add them repeatedly, but without effect:

>>> S.add (4) >>> s{1, 2, 3, 4}>>> S.add (5) >>> S{1, 2, 3, 4, 5}


You can delete an element by using the Remove (key) method:

>>> S{1, 2, 3, 4, 5}>>> s.remove (4) >>> s{1, 2, 3, 5}



Set can be regarded as a set of unordered and repeating elements in the numerical sense, so that two sets can do the intersection and set of mathematical meanings, and so on:

>>> S1 = set ([]) >>> s2 = set ([2,3,4]) >>> s1&s2{2, 3}>>> s1|s2{1, 2, 3, 4}


The only difference between set and dict is that it does not store the corresponding value, but the principle of set is the same as dict, so it is not possible to put mutable objects, because two

Variable objects are equal and do not guarantee that the set has "no duplicate elements" inside it. Try putting the list in set to see if it will give an error.

>>> a=[1,2,3, ' a list ']>>> a[1, 2, 3, ' a list ']>>> B = Set ([1,a])
Traceback (most recent): File "<pyshell#59>", line 1, in <module> B = Set ([1,a]) Typeerror:unhas Hable type: ' List '



Re-discussing non-mutable objects

As we learned from the above, Str is an immutable object, and list is a mutable object.

For mutable objects, such as list, to manipulate the list, the contents of the list will change, such as:

>>> a = [' C ', ' B ', ' A ']>>> a.sort () >>> a[' A ', ' B ', ' C ']

For non-mutable objects, such as STR, we operate on STR:

>>> a = ' abc ' >>> a.replace (' A ', ' a ') ' abc ' >>> a ' abc '


Although the string has a replace () method, it does change the ' ABC ', but the variable a finally remains ' abc '

How should we understand it?

Let's Change the code:

>>> a= ' abc ' >>> b=a.replace (' A ', ' a ') >>> B ' abc ' >>> a ' abc '

A is a variable, and ' abc ' is a String Object! Sometimes, we often say that object A's content is ' abc ', but actually

means that A is itself a variable, and the content of the object it points to is ' abc ':

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/14/wKiom1b2jeWAthb6AAAG-BqIIZs060.png "title=" Image.png "alt=" Wkiom1b2jewathb6aaag-bqiizs060.png "/>

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>

When we call A.replace (' a '. ') A '), the actual call method replace is on the string object ' abc ', and this method, although named Replace, does not change the contents of the string ' abc '. Instead, the Replace method creates a new string ' abc ' and returns, if we point to the new string with variable B, it's easy to understand that variable a still points to the original string ' abc ', but the variable B points to the new string ' abc ':

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/7E/10/wKioL1b2jpTxWJdxAAAMHTbvoD4654.png "title=" Image ( 2). png "alt=" Wkiol1b2jptxwjdxaaamhtbvod4654.png "/>

This article is from the "Creative Pilgrim" blog, so be sure to keep this source http://dearch.blog.51cto.com/10423918/1755546

According to Liao Xuefeng python3 tutorial----python study sixth day

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.