Python Advanced Training

Source: Internet
Author: User

1, list, dictionary, set parsing

From the random import randint# list resolution, select elements greater than 0 data=[randint ( -10,10) for I in range]result1=filter (lambda  x:x>=0, Data) result2=[x for x in Data if x>=0] #最快for x in data: #最慢    if x>=0:        print (x) #字典解析, value greater than 80d = {X:randint (60 , (1,20)} #构造字典result3 ={k:v for k,v in D.items () if V>80}print (RESULT3) #集合解析
#集合中科院被3整除的元素

Result4={x for x in S if x%3 ==0}

2. Name the tuple

#可命名元组from Collections Import namedtuple# First way student = (' BOB ', +, ' male ', ' [email protected] ') Name,age,sex,email = Range (4) print (Student[name])

  

From collections import namedtuple# First Way # student = (' BOB ', +, ' male ', ' [email protected] ') # Name,age,sex,email = Range (4) # print (Student[name]) student= namedtuple (' Student ', [' name ', ' age ', ' sex ', ' email ']) s=student (' Jim ', ' Male '), ' [ Email protected] ') print (S, ' ========== ', s.name)

Execution results

3. Frequency of elements appearing in statistical sequences

From random import randintdata = [Randint (1,20) to x in Range] #随机序列, calculates the number of occurrences of each element C=dict.fromkeys (data,0) #0是初始值, ; keyfor x in data:    c[x] +=1 The elements in the list as dictionaries

  

From random import randintdata = [Randint (1,20) to x in range] #随机序列, calculate the number of occurrences of each element from collections import Counterc2  = Counter (data) C2.most_common (3) #哪三个元素出现最多print (C2,c2.most_common (3))

Results

Word Frequency statistics

Import Refrom Collections Import Countertxt = open (' A.txt '). Read () c1=re.split (' \w ', txt) #对非字母进行分割, and then pass in Counterresult = Counter (c1) #将列表传进去res = Result.most_common (3) #出现次数最多的三个单词

4. Sort the items in the dictionary according to the size of the values in the dictionary

From the random import Randintd1={x:randint (60,100) for x in ' abcxyz '} #六个人分别叫abcxyz #1print (sorted (Zip (d1.values (), D1.keys ())) #元组组成的列表, compares the first element of a tuple #2print (sorted (D1.items (), Key=lambda x:x[1])

Results

5. How to quickly find common keys in multiple dictionaries

The from random import Randint,sample#sample is sampled #1sam=sample (' ABCdef ', Randint (3,6)) #随机选取 ' abcdef ' three to 6 samples S1 ={x:randint ( 1,4) for X-in-sample (' ABCdef ', Randint (3,6))}s2={x:randint (1,4) for X in sample (' ABCdef ', Randint (3,6))}s3={x:randint ( 1,4) for x in the sample (' ABCdef ', Randint (3,6))}print (S1,S2,S3) for K in S1:    if k in S2 and K in S3:        print (k)

Results

The second method of

Print (S1.keys () & S2.keys () & S3.keys ()) #python2是viewkeys, where you take the intersection from Functools import reduceprint (Reduce ( Lambda A,b:a & B,map (Dict.keys,[s1,s2,s3])) #如果键多可以这样, Python2 is Viewkeys

6, how to make the dictionary orderly

From collections import  ordereddictd= ordereddict () d[' jib ']= (1,35) d[' Bob ']= (2,5) d[' BBC ']= (3,5) for i in D:    Print (i)

Results

7. Splitting a string containing multiple separators

s= ' Ab;cd|efgh|hi,jkl|topq;rst,vww\atex ' t=[]res = S.split (';') Map (Lambda X:t.extend (X.split (')), res) print (t)

The second method of

Import res= ' Ab;cd|efgh|hi,jkl|topq;rst,vww\atex ' Print (Re.split (R ' [,; \|] ', s))

Results

8. Judging the beginning of a string

9, regular adjustment text format

Import re#1l=[' 2016-05-23 ', ' 2016-06-11 ', ' 2016-07-12 ']l1= ' 2016-05-23 ' Print (Re.sub (' (\d{4})-(\d{2})-(\d{2}) ', R ' \2 /\3/\1 ', L1))

Results

The second method of

Import re#1l=[' 2016-05-23 ', ' 2016-06-11 ', ' 2016-07-12 ']l1= ' 2016-05-23 ' Print (Re.sub (? P<YEAR>\D{4})-(? P<MONTH>\D{2})-(? P<day>\d{2}) ', R ' \g<month>/\g<day>/\g<year> ', L1)

10. String concatenation

The first of these methods

But this method wastes memory, here is the second method, with the join

11, adjust the center of the string, align left and right

s= ' abc ' Print (s.ljust) print (S.ljust (+, ' + ')) print (S.center (20, ' + '))

Results

Ling Another way

12. Remove unwanted strings

Remove spaces

Remove a specified character

s= ' abc__++++ ' Print (S.strip (' _+ ')) S1 = ' abc:1224 ' Print (s1[:3]+s1[4:])

Results

s= ' \tadhi\sfds\sdfds\sdfds\gf\gs\ggg ' Print (Re.sub (' [\t\g\f\d] ', ', s))

  

Python Advanced Training

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.