Cloud Classroom-python Learning notes (7)

Source: Internet
Author: User

First, the dictionary

1. What is a dictionary

1. A series of key-value (Key-value) pairs
2. Find the corresponding "value" by "key"
3, similar to the paper dictionary, through the Word Index table to find its corresponding definition
C++:map, java:hashtable or HashMap
Example: Phone book

2. Create a dictionary

Use {} to create a dictionary

Use: Specify key: Value pair
my_dict={' John ': 86411234, ' Bob ': 24896880, ' Mike ': 354859977}

3. Access to the dictionary
Using the [] operator, the key as the index
Add a new pair of

 1  my_dict={ " john   ": 86411234,"   Bob  : 24896880,"  mike  : 354859977 2  print  my_dict[ " john   " ]   my_dict[ " tom   ' ] = 98644336794  print  my_dict 

4. Dictionary operators and methods

1 len (my_dict): Number of key- value pairs in a dictionary 2 in my_dict: Quickly determine if key is a key in the dictionary: Time Complexity O (1)3  equivalent to My_dict.has_key (key)4 for in my_dict: The key in the enumeration dictionary, note: The key is unordered

More ways:

1 my_dict.items (): All keys- value pairs 2My_dict.keys (): All keys 3My_ Dict.values (): Full value 4 my_dict.clear (): Empty dictionary

5. Example 1: Read a string to calculate the number of occurrences of each letter

Scenario One: Generate 26 variables representing the number of letters appearing

Scenario Two: Generate a list of 26 elements, converting each letter to the index value of the object

1 ' Abdddeyyyrewgq ' 2 lst = [0]*263 for in s:4     Lst[ord (i) -97] +=15     6print LST

Scenario Three: Generate a dictionary, the letter to do the key, corresponding to the number of occurrences of the value

s =={} for in s:    if in D:        + = 1    Else :         = 1    print D

Example 2: Read a novel emma.txt, print the first 10 most common words

1F= Open ('Emma.txt')2Word_freq = {}3  forLineinchF:4Words =Line.strip (). Split ()5      forWordinchwords:6         ifWordinchWord_freq:7Word_freq[word] + = 18         Else:9Word_freq[word] = 1Ten              OneFreq_word = [] A  forWord,freqinchWord_freq.items (): - Freq_word.append ((Freq,word)) -Freq_word.sort (reverse =True) the  -  forFreq,wordinchFreq_word[:10]: -     PrintWord -F.close ()
View Code

Example 3: Flipping a dictionary: generating a new dictionary whose key is the value of the original dictionary with the key of the original dictionary

1D1 = {'Zhang': 123,'Wang': 456,'Li': 123,'Zhao': 456}2D2 = {}3  forName,roominchD1.items ():4     ifTheinchD2:5 d2[room].append (name)6     Else :7D2[room] =[Name]8 PrintD2
View Code

Two, set (set)

1, set: unordered element set, similar to dictionary, but no value
2. Create:
x = Set ()
X={key1,key2,....}
3. Add and remove
X.add (' body '
X.remove (' body ')
4, set of operators:
-: Difference Set
&: Intersection
|: and set
! =: Not equal to
= =: equals
In: Members
For key in set: enumeration
5. Example: Chinese participle
I/Love/Beijing/Tiananmen
Algorithm: Forward maximum match
Take long words from left to right

1 defload_dict (filename):2Word_dict =set ()3Max_len = 14f =open (filename)5      forLineinchF:6Word = Unicode (Line.strip (),'Utf-8')7 Word_dict.add (Word)8         ifLen (word) >Max_len:9Max_len =len (Word)Ten     returnmax_len,word_dict One  A deffmm_word_seg (sent,max_len,word_dict): -Begin =0 -Words = [] theSent = Unicode (Sent,'Utf-8') -      -      whileBegin <Len (Sent): -          forEndinchRange (begin + Max_len,begin,-1): +             ifSent[begin:end]inchword_dict: - words.append (Sent[begin:end]) +                  Break ABegin =End at     returnwords -Max_len,word_dict = Load_dict ('Lexicon.dic') -  -Sent = Raw_input ('Input a sententce:') -Words =fmm_word_seg (sent,max_len,word_dict) -  forWordinchwords: in     PrintWord
View Code

Cloud Classroom-python Learning notes (7)

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.