Python Advanced Learning Chapter02 (list, dictionary, collection Operations)

Source: Internet
Author: User

    1. How to filter data in lists, dictionaries, collections
    2. Renaming of lists (tuples)
    3. The realization of Word frequency statistic
    4. Sort of dictionary
    5. Find common keys for multiple dictionaries
    6. How to keep the dictionary in order
    7. How to keep track of history (using deque queue)

How to filter data in a list, dictionary, collection

Problem Introduction:

List: [ -10,2,2,3,-2,7,6,9] Find all non-negative numbers

Dictionary: {1:90,2:55,3:87 ...} to find all key-value pairs with values greater than 60

Collection: {2,3,8,6,7,5} Find all the numbers that are divisible by 3

List:

#方法一, iterate data=[1,5,-4,-6,0,7,9]res=[]for num in data:    if num >=0:        res.append (num) print (res) #方法二, Filter function Filterres1=filter (lambda x:x>0,data) print (list (res1)) #方法三, List Builder [x for x in data if x >= 0]

Dictionary:

#字典students ={x:randint (30,100) for x in range (1,21)}print (students) #筛选处成绩80分以上的, items () traverse both the key and the value res4={k:v for k,v in Students.items () if V>=90}print (RES4)

Collection:

#集合set =set (data) res5={x for x in Set if X%2==0}print (RES5)

Ii. renaming of lists (tuples)

Problem Introduction:

1 = (' sun ', ' + ', ' girl ', ' [email protected] ') print (s1[0])

Use the number as an index to the array, read when the readability is too poor, you can change the name

Name=0age=1sex=2email=3print (S1[age])

or import Namedtuple

From collections Import namedtuplestudents=namedtuple (' Student ', [' name ', ' age ', ' sex ', ' email ']) #定义一个类s2 =students (' Sun ', ' + ', ' girl ', ' [email protected] ') #实例化一个类print (type (s2)) print (S2.email) #相当于调用实例的属性

Three, the realization of the word frequency statistic

Problem Introduction:

[6, 7, 5, 9, 4, 1, 8, 6, 2, 9]

We hope to count the number of occurrences of each element, which can be regarded as a question of frequency statistics.

We want to end up with a result like this: {6:2, 7:1 ...} {An element: The number of occurrences ...}

#方法一list =[randint (1,10) for x in range (Ten)]print (list) D=dict.fromkeys (list,0) for x in list:    d[x]+=1print (d) # Method two from Collections import Counterd1=counter (list) print (D1) print (D1.most_common (3))

The Dict.fromkeys () method is used to create a new dictionary, passing in two parameters, sequences, and initial values. Http://www.runoob.com/python/att-dictionary-fromkeys.html

Collections's counter module, see the next article

Iv. Ordering of dictionaries

Problem Introduction:

The Python dictionary itself is unordered and the order of each visit is random. We can sort the dictionaries by using sorted, but the sorted function simply sorts the keys of the dictionary without considering the values

What if you need to sort the following dictionary by value? {' Tom ': All, ' Jack ': All, ' Rose ': 100 ...}

Method One, use the ZIP function to package the Narimoto group for each pair (value, key) of the dictionary, and then sort by sorted. Zip function: http://www.runoob.com/python/python-func-zip.html

Dict={x:randint (60,100) for x in ' ABCdef '}print (dict) print (sorted (Zip (dict.values (), Dict.keys ()))

Method Two, the sorted function itself can be passed to a key, and then can follow the specified key sort, sorted function is still very powerful, http://www.runoob.com/python/python-func-sorted.html

Students = [(' John ', ' A ', '), (' Jane ', ' B ', '), (' Dave ', ' B ', ten)]>>> sorted (students, KEY=LAMBDA s:s[2])            # sorted by age [(' Dave ', ' B ', ' Ten '), (' Jane ', ' B ', '), (' John ', ' A ', 15)]

  

Find common keys for multiple dictionaries

Problem Introduction: How to find the players who have scored in every three games

Mister into analog data:

From random import randint,sample
S1 = {X:randint (1,3) for X in sample (' ABCdef ', Randint (3, 6)}
S2 = {X:randint (1,3) for X in sample (' ABCdef ', Randint (3, 6)}
S3 = {X:randint (1,3) for X in sample (' ABCdef ', Randint (3, 6)}

{' C ': 1, ' E ': 3, ' B ': 1}
{' C ': 3, ' d ': 1, ' B ': 2}
{' E ': 3, ' a ': 2, ' F ': 2, ' B ': 1}

Method One, Traverse

Res=[]
For x in S1:
If x in S2 and X in S3:
Res.append (x)
Print (RES)

[' B ']

Method Two, and the operation

Print (S1.keys () &s2.keys () &s3.keys ())

Method Three, use map and reduce. After the usage of map and reduce, the article introduces separately

>>> map (Dict.viewkeys, [S1, S2, S3]) [Dict_keys ([' A ', ' B ', ' F ']), Dict_keys ([' A ', ' B ', ' e ', ' d ', ' G ', ' f ']), dict_ Keys ([' A ', ' B ', ' e ', ' d ', ' F '])]>>> reduce (lambda x,y:x&y, Map (Dict.viewkeys, [S1, S2, S3])) Set ([' A ', ' B ', ' F '])

V. How to keep the dictionary in order

The dictionary itself is unordered, and if it is necessary to maintain the order of entry when it is accessed, you can use collections's ordereddict

From collections Import ordereddictd=ordereddict () d[' Sun ']= (1,35) d[' Yue ']= (2,37) d[' ru ']= (3,40) for i in D:    print ( i) Sunyueru

  

Vi. Save history (using Deque queue)

How do I save a number that you've guessed in a number game?

Let's take a look at the version of the guessing number game without saving:

From collections import Dequefrom random Import randintn = randint (0, MB) def guess (k):    if k = = N:        print "right" 
   return True    If k < n:        print "%s is Less-than n"% k    if k > N:        print '%s is Greater-than n '% k
   return falsewhile True: Line    = raw_input (' Please input a number: ')    if Line.isdigit ():        k = int (line)            If Guess (k): Break              

If the number of each guess is stored in the queue, if the user enters history to output the guessed number, version two:

From collections import Dequefrom random Import randintn = Randint (0, +) History= Deque ([], 5)def guess (k): 
   
    if k = = N:        print "right"        return True    if k < n:        print '%s is Less-than n '% k    if k > N:        prin T '%s is Greater-than N '% K    return falsewhile True: line    = raw_input ("Please input a number:")    if Line.isdig It ():        k = int (line)     
       history.append (k)        if guess (k):            break   
     elif line = = ' history ' or line = = ' h? ':        Print List (history)
   

If you still need to save this queue, the next time you re-execute the program can be used, you can use the Pickle module

Save first

>>> import pickle>>> s = [1, 2, 3, 4, 5]>>> pickle.dump (S, open (' object ', ' W ')) >>> # This The S object exists in this file, and the file has a write permission

Next time you can read

>>> Import pickle>>> s = pickle.load (' object ') >>> s[1, 2, 3, 4, 5]

  

Python Advanced Learning Chapter02 (list, dictionary, collection Operations)

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.