Summary of Python work

Source: Internet
Author: User

The following methods are seldom used and other solutions are used to summarize some other colleagues ' skills.

1 How to automatically generate lists, plus a condition to filter

[x for X in range (ten) if X>5]

Try a dictionary in the afterlife

D = {X:randint (60,100) for x in range (1,21)}//Randint need to import package

From random import Randint

Filter the dictionary method with iteration

{k:v for k,v in D.iteritems () if v>90}//Iteritems () Py3 also renamed

D.items ()

How to name each element in no group

Studen = ("Xsy", +, "13575665", "[email protected]")

Such data is saved as a tuple to save memory, and access can be

#name

STUDEN[0]

#age

STUDEN[1]

The above method accesses, but the code is more, the number represents what is not intuitive

Python mimics the C-Write enumeration method to resolve: 1, define some constants first

NAME =0

Age = 1

SEX = 2

EMAIL = 3

Advanced definition Methods

Name,age,sex,emae = Range (4)

The following examples use

Print (Student[name])//

If studen[age]>=18k

If student[sex] = = "Male"

Method two, construct with class

From collections Import Namedtuple
Student = Namedtuple ("Student", [' Name ', ' age ', ' sex ', ' xx '])
s = Student ("Jim", +, ' male ', ' [email protected] ')
Print (S.name)
Print (Isinstance (s,tuple))//true, meaning can be used in a group of places can use this method





Number of occurrences of the list element

From random import Randint

[Randint (0,20) for X in Rnage (30)]//will generate 30 random numbers now we want to count to a dictionary such as {8:2,7:6} 8 appears 2 times, 7 appears 6 times. This way

D =[randint (0,20) for X in Rnage (30)],

Eventually become

c= {2:6,6:4 ...}.}

Complete the function code as follows

From random import Randint
D =[randint (0,20) for X in range (30)]
c = Dict.fromkeys (d,0)
For x in D:
C[x]+=1
Print (c)

Summary of Python work

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.