Basic grammar of Python learning notes

Source: Internet
Author: User
Tags pear


    • Three ways to import a function

From math import sqrt #import the SQRT function is e.g. sqrt from math import * #import all functions from M Ath module e.g sqrt import math #import math Module,and use the function via math.* e.g. MATH.SQRT (25 )
    • Comparison of type functions

Def Distance_from_zero (a): if (Type (a) ==int or type (a) ==float): #the type function return the type of the parameter , and when compare-Type,don ' t round it with quotation mark return ABS (a)
    • List array

#分割数组letters  = [' A ',  ' B ',  ' C ',  ' d ',  ' E ']   slice =  letters[1:3]      #slice  will get letters[1] and letters[2]  ,but no letters[3]print sliceprint letters# Gets the index animals = ["Aardvark" based on the specified value,   "Badger",  "Duck",  "emu",  "Fennec fox"]duck_index = animals.index ("Duck")     #在指定索引位置插入值animals. Insert (Duck_index, "Cobra") #将指定数组值删除. removebackpack = [' Xylophone ',  ' dagger ',  ' tent ',  ' Bread loaf ']backpack.remove (' dagger ') #删除数组元素的三个函数 #1.     n.pop (Index) #n. Pop (index)  will remove the item at index  From the list and return it to you:n = [1, 3, 5]n.pop (1 )     # Returns 3  (the item at index 1) print n      #&nBSP;PRINTS [1, 5] #2.     n.remove (item)  will remove the  Actual item if it finds it:n.remove (1)   # removes 1 from  the list,NOT the item at index 1print n       # PRINTS [3, 5] #3.     del (n[1])  is like .pop in  that it will remove the item at the given index, but  it won ' T return it:del (n[1])    # doesn ' t return  ANYTHINGPRINT N     # PRINTS [1, 5] #list数组的for循环start_list  =  [5, 3, 1, 2, 4]square_list = []for number in start_list:        #依次从start_list取值存入变量number中     square_list.append (  number ** 2 )           #对取出的值平方后追加给square_listsquare_list. Sort ()                            #对square_list排序print An array of  square_list# arrays n = [[1, 2, 3], [4,  5, 6, 7, 8, 9]] #将数组lists中的所有数组的值取出形成一个新的数组def  flatten (lists):     results=[]    for numbers in lists:         for number in numbers:             results.append (number)     return resultsprint flatten (n) #数组切割, The use of sequential, reversed # array cutting is quite flexible, and the basic syntax is [Start:end:stride], by default, Start=0,end=len-1,stride#=1. When the stride is positive, the cut will proceed sequentially, starting from 0, and when the stride is negative, the cut will be reversed, i.e. from the last   #一个元素开始. In the following example, one character is taken from the last element garbled =  "! Xexgxaxsxsxexmx xtxexrxcxexsx xexhxtx xmxax&nbSp XI "Message=garbled[::-2]print message
    •      dictionary

menu = {} #  Create an empty dictionary menu[' Chicken alfredo '] = 14.50   # Add key value pair menu[' Tomato and eggs '] = 11menu[' frid apple '] = 9.8menu[' Tu Dou ' ] = 16.5del menu[' Frid apple ']               #删除键值对menu [' Tu dou ']=10                    #修改key对应的值print   "there are "  + str ( Len (menu))  +  " items on the menu."   #取字典长度len (menu) The data type of key-value pairs in the print menu# dictionary can vary inventory = {     ' gold '  : 500,     ' pouch '  : [' flint ',  ' twine ',  ' gemstone '], #  Assigned a new list to  ' pouch '  key     ' backpack '   :  [' xylophone ', ' dagger ',  ' bedroll ', ' Bread loaf ']}# adding a key  ' Burlap bag '  and assigning a list to  itinventory[' burlap bag '] = [' apple ',  ' Small ruby ',  ' Three-toed sloth ']#  Sorting the list found under the key  ' pouch ' inventory[' pouch '].sort ()  #  Add a key-value pair, the value of the key-value pair is listinventory[' pocket '] = [' seashell ', ' strange berry ', ' Lint ']# The reference to the list array in the   dictionary is basically no different from the reference to the array itself inventory[' backpack '].sort () inventory[' backpack '].remove (' dagger ') inventory[' The For loop in the gold '] = inventory[' Gold '] + 50# dictionary, consistent with list webster = {"Aardvark"  :   "A star of a popular children ' s cartoon show.",      "Baa"  :  "The sound a goat makes",     "Carpet":  " Goes on the floor. ",    " Dab ": " A small amount. "} #  the value of all keys in the output Webster FOR WEB IN&NBAn application instance of the For loop in the sp;webster:    print webster[web]    #  dictionary prices  = {     "Banana": 4,     "apple": 2,      "Orange": 1.5,     "pear":  3}    stock =  {     "Banana": 6,     "apple": 0,      "Orange": 32,     "pear":  15}    for key in  prices :    print key    print  "price: %s"% ( Prices[key])       #注意输出字符串的拼接     print  "stock: %s"% ( Stock[key]) ######################################################################################     Little Practice ######################################################################################   Lloyd = {                                 #student  lloyd     " Name ": " Lloyd ",    " homework ": [90.0, 97.0, 75.0, 92.0],      "Quizzes": [88.0, 40.0, 94.0],     "tests":  [75.0,  90.0]}alice = {                                #student  alice     "Name":  "Alice",     "homework": [100.0,  92.0, 98.0, 100.0],     "Quizzes": [82.0, 83.0, 91.0],      "tests": [89.0, 97.0]}tyler = {                                 #student  tyler     "name":  "Tyler",     "homework":  [0.0, 87.0, 75.0, 22.0],     "Quizzes": [0.0, 75.0,  78.0],     "tests":  [100.0, 100.0]}def average (Numbers):                 #get  the average of  a list of numbers    total = float (sum (numbers))      aver = total / len (Numbers)     return aver     def get_average (student):            #get  the average grade of any student    homework  = average (student["homework"]) &nbsP;   quizze = average (student["quizzes")     test =  Average (student["tests"])     return 0.1 * homework + 0.3 *  quizze + 0.6 * test    def get_letter_grade (Score):         #get  letter grade,like  "A"/"B"/"C"      if (score>=90):        return  "A"     elif ( score>=80):        return  "B"     elif ( score>=70):        return  "C"     elif ( score>=60):        return  "D"     else:         return  "F" Print get_average (Lloyd)             #get  the average grade of lloyd#get the average class  Grade of all students in the classdef get_class_average (students):     results=[]    for student in students :           results.append (Get_average (student))      Return average (results) class_average=get_class_average ([Lloyd,alice,tyler]) Print class_averageprint  get_letter_grade (class_average) #python内置字典函数 #.items () will take out the key-value pairs of the dictionary separately, such as ("Monty python and the  holy grail ":" Great ") #.keys () will take out the dictionary key #.values () will take out the value of the dictionary separately movies = {" Monty python  and the holy grail ": " Great "," Monty python ' S life of brian ":   "Good", "Monty python ' S meaning of life":  "Okay"}print movies.items ()
    • Range ()

#The Range function has three different versions: #range (stop) #range (start, stop) #range (start, stop, step) #In all cases, th E range () function returns a list of numbers from start-to (and not including) stop. Each item is increases by step #If omitted, start defaults to zero andstep defaults to One.range (6) # = = [0,1,2,3, 4,5]range (1,6) # = [1,2,3,4,5]range (1,6,3) # = [1,4]
    • Filter () and lambda function

#lambda函数与filter () combinations are useful. Lambda defines an anonymous function, and the following example, X: (X%3==0 or x%5==0), means that if x can be divisible by 3 or 5, then X is returned. The filter function, in turn, takes the elements in the num_15 as the # input for the lambda function. Num_15=range (1,16) Threes_and_fives=filter (lambda x: (x%3==0 or x%5==0), num_15)


This article is from the "Deathlesssun" blog, make sure to keep this source http://deathlesssun.blog.51cto.com/3343691/1662932

Basic grammar of Python learning notes

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.