Python Notes - Memo

First, add an element to the list

  x.append (y) # an element added to the end
  x.extend ([y, z]) # plurality of elements added at the end
  x.insert (index, y)

Second, to get a list of elements  
  x [index]

Third, remove elements from the list
  ( "the y-") x.remove
  del the X-(index) # delete the entire list of the X-del
  x.pop () # pop the last element of the list x.pop (index) index corresponding elements of pop

Fourth, the list slicing (to create a copy)
  X [X: Y] #x is the starting position, y is the end position of the end position does not contain
  x [x: y: z] #z default step size is 1 z -1, reverse the number of columns

V. List
  x.count (y) # How many times to calculate x y appear
  x.index (y) # Returns the y position in x
  x.reverse () # list reversal
  x.sort () # from small to large sort (fun, key = None, reverse = False)

Six tuple (. 1,)
  X = (A, B, C, D, E, F, G, ...)  
  access tuples: x [index]  
  slice replication tuple x2 = x1 [:]
  Indirect Delete the third element x = x [: 2] + x [3:]
  delete tuples del x

Seven, fotmat format (012format parameter for the location parameter, ABC label, format parameters will be substituted into the contours, i.e. keyword arguments, parameters must position before the keyword parameter)
  "Love {{0}}. 1. {2} ". format (" I "," baidu "," com ") # i.e. 'the I Love Baidu.com'
  " Love {A} {B}. {C}. "the format (A =" the I ", b = "baidu", c = "com") # i.e. 'the I Love Baidu.com'
  "{0}: {. 1: .2f}." the format ( "pi", 3.14159) # is the 'pi: 3.14' added 1 position parameters: replacement field, a colon indicates the beginning of the formatting, .2 represents rounded to 2 decimal places

Eight, import timed
  Import datetime
  Start = datetime.datetime.now ()
  ...
  ...
  Delta = (datetime.datetime.now - Start) .total_seconds ()
  Print (Delta)

Nine, digital processing
  Import Math   
  Math.floor () # floor rounded down int   
  Math.ceil () # ceiling rounding up. 5 = 4.5 of 5
  math.trunc () # 0 in the direction of orientation
  round () # membered whole rounded six up 5 rounded to the nearest even number  

  math.sqrt () # prescribing
  POW (the X-, the y-) the X-** == the y-
  bin () # Binary
  oct () # octal
  hex () # hex
  Math.PI # pi
  Math.E

Ten, the type of judgment
  type () # returns type type
  isinstance (int, str) # is int is an instance of str? ?

XI List [list]
  can be any object (number, string objects, list)
  several elements ordered, variable
  []
  query, a [index]
    time complexity of O (x) x traversing element
  assignment : list [x] = value
  delete: a.clear () # remove, leaving an empty list
    a.remove (value) # remove a value
    a.pop ([index]) # default pop-up last value
  else:
    a .reverse () -> None #-place changes reverse sequence
    a.sort (key = None, reverse = False) -> None # -place sorted in ascending order by default a key function to specify how the sort key
  list to copy:
    == comparison value ( content); IS comparing memory address
    lst1 = lst0 no assignment process

    A = [l, 2,3]
    B = A [:]

    copy-> list (shadow copy) x.copy () in order to re-create the
    shadow copy and shallow copy just copy a reference to the
    deep copy deepcopy -> import copy


  enumerate (iteralbe) # generated by the tuple (a tuple number of elements of two) iterables constituted
            each by a tuple element in the iteration index, and composition of the object corresponding to
    a normal loop for
      >>> I = 0
      >> > SEQ = [ 'One', 'TWO', 'Three']
      >>> for Element in SEQ:
      ... Print I, SEQ [I]
      ... = I +. 1
      ...
      0 One
      . 1 TWO
      2 Three

      for 循环使用 enumerate
      >>>seq = ['one', 'two', 'three']
      >>> for i, element in enumerate(seq):
      ... print i, element
      ...
      0 one
      1 two
      2 three

  zip () function is used to be the object as a parameter the iteration, the corresponding element of the object packed into a tuple and returns a list of these tuples.
    If the number of elements of each iterator inconsistency, the shortest length of the list and returns the same object, using the asterisk operator, tuples will extract the list.

      A = >>> [l, 2,3]
      >>> B = [4,5,6]
      >>> C = [4,5,6,7,8]
      >>> zipped ZIP = (A, B ) # packaged as a list of tuples
      [(1, 4), (2,. 5), (. 3,. 6)]
      >>> ZIP (a, C) and the number of elements in the list # consistent shortest
      [(1, 4 ), (2,. 5), (3,. 6)]
      >>> zip (* zipped) and zip contrast #, * zipped understood to be decompressed, to return a two-dimensional matrix
      [(1, 2, 3), (4 , 5, 6)]

Twelve, random number
  Import Random
        the random.randint (A, B) Returns the integer [#] ab between
     random.choice (seq) # non-empty list from a randomly selected number
     random.randrange ([start,] stop) [ , step]) # Gets a random number incremented by the specified base set, the default value cardinality. 1
     random.shuffle (list) disrupted in situ list element #

XIII tuple (tuple) immutable
  tuple () -> empty tuple
  T = (. 1,)
  access tuples index
  query index (value, [Start, [STOP]])
  COUNT (value) count

  Tuple named namedtuple (typename, field_name, verbose = False, rename = False)
    named tuple returns a tuple of the subclass, and defined fields
    field_name string field can be divided in space or comma, the field may be list
  introduced from collections import namedtuple
    Example: Point = namedtuple ( 'P [name]', 'X, Y')
    P1 = Point (4,5)

  Delete: del tuple

XIV Dictionary {dict}
  Create: {}
      {Keys: value}
      dict (Key = value)
      dict ([(Key, value), (Key, value),])
  dict1 = dict ((( 'F.', 70 ), ( 'A, 80'), ( 'S', 90))) // dict (F. = 70, A = 90, S = 90)
      doct1 => { 'F.': 70, 'A': 80 , 'S': 90}

  fromkeys () # creates and returns a new dictionary: the first two parameters of a key [is a second value]
    dict1 = {}
    Keys = [ 'name', 'Age', ' Job ']
    employ = dict.fromkeys (Keys)
    employ => {' NAME0 ': None,' Age ': None,' Job ':} None

    dict1.fromkeys((1,2,3)) => {1:None,2:None,3:None}
    dict2.fromkeys((1,2,3),"Number") = > {1:"Numbwe",2:"Number",3:"Number"}

  Accessing the dictionary: keys () return key, values () Returns the value of all the dictionary, items () Returns all entries
    dict1 = {}
    dict1 = dict1.fromkeys (Range (. 3), 'Hello')
    dict1.keys () => dict_keys ([0,1,2])
    dict1.values () => dict_values ([ 'Hello', 'Hello', 'Hello'])
    dict1.items () => dict_items ([(0 , 'Hello'), (1, 'Hello'), (2, 'Hello')])

    get () # When the key does not exist. Back None
    dict1.get (31 is) => 'Hello' dict.get (32) =>
    if found, may be disposed in the second parameter values
    is determined whether there is: index in dict1

    setdefault () # when the bond is absent, automatically add None

  Update dictionary:
    Data [Key] = value
    Qucik Facts Pets = { 'Mickey', 'rat', 'Tom', 'Bobby'}
    pets.update (Mitch = 'Cooskin')
    Qucik Facts Pets => { 'cool odd', ' mouse ',' Tom ',' Bobby '}

  Empty dictionary:
    dict.clear ()
  Copy:
    dict2 = dict1.copy () the above mentioned id = 1 2!
  Merge:
    data1.update (data2)

  POP () popitem ()
    dict1.pop (2) # corresponding pop-up key
    dict2.popitem () # a pop just want to
  delete the value:
    del the Data [Key]

  function is assigned to a value: behavioral approach
    DEF say_hello ():
      Print ( 'welcome')

    person = {'name':'Jerry','hello':say_hello}
    person['hello']() -> welcome

XV string immutable objects can be ordered iteration

  '[]' join (str) .
  Processing: ~ split series (cut) by a string delimiter o cut into several string and returns a list
    ~ s.partition (sep) -> ( head, sep, tail) series will press string delimiter cut into 2 segments, and the segments 2-tuple returns delimiters
      from left to right, put the string delimiter is encountered divided into two parts, the first return, separator, the end of three parts
      if the partition is not found Fu, returns the head, two triples empty elements
      sep split the string. Must be specified
    s.rpartition (sep) -> (head , sep, tail)
      from right to left, put the string delimiter is encountered divided into two parts, the first return, the separator, the end of three parts
      if the delimiter is not found, 2 back to the tail of empty elements and triples
    split (sep = None, maxsplit = -1) -> list of strings
      specified character string from left to right is divided sep. Empty string as a separator case of default
    number specified masxsplit split, through the entire string of -1 indicates
      segmentation * splitliness ([keepends]) - > list of strings
       in accordance with the cut line to retain the string keepends refers to whether line delimiter (\ n \ t \ r)

  String case
    s.upper () # all uppercase
    s.lower () # all lowercase
    case, to make a judgment when using swapcase () interact sensitive

  string layout
    title () -> str title of each word capitalized
    s.capitalize () -> str the first word capitalized
    s.center (width [, fillchar]) -> str width print width fillchar filled character
    s.zfill (width) -> str width print width, the right home, left with 0 supplementary
    s.ljust (width [, fillchar]) -> str left
    s.rjust (width [, fillchar]) -> str right justified

  String modify
    s.replace (old, new [, count ]) -> str string match is found, replaced with a new string and returns a new string count represents several alternatives, the default Replace All
    s.strip ([chars]) - > str remove all the characters from both ends of the character string specified by the default set chars to remove blank

    s.lstrip ([chars]) -> from the left
    s.rstrip ([chars]) -> right start

  String search *
    s.find (sub [, Start, End]]) -> sub int lookup from left to right (substring) Returns the index has not, returns -1
    s.rfind (sub [, Start, End]] ) -> int right to left to find sub (substring) returns the index has no, or -1

    s.index (sub [, start [, end]]) -> int find sub (substring) from left to right with a return without index, Throws
    s.rindex (sub [, start [, end]]) -> int right to left to find sub (substring) has no return index, Throws

    Time complexity of O (n)
    times> int [specified interval) occurring from left to right statistical sub - s.count (sub [, start [, end]])

  Analyzing the string *
    endsWith (suffix [, Start [, End]]) -> BOOL in the specified range, the end of the suffix string is
    startwith (prefix [, start [, end]]) -> bool in the specified range, whether the string the beginning of the prefix

  Series string is determined
    isalnum () -> bool whether the letters and numbers
    isalpha () -> bool whether the letter
    isdecimal () contains only decimal digits
    isdigit () whether all numbers (~ 0. 9)
    isIdentifier () is not letters and underscore the beginning, others are letters, numbers, underscores
    islower () whether all lowercase
    isupper () whether all uppercase
    isspace () contains only whitespace characters

  *** string formatting
    + string concatenation non-transformed string to
    join the separator and the splice can be used for splicing iterable
    format requirements: placeholder format% (values) (only one object, or equal to the number of tuples)

  The format ***
    "XXX {} {}" the format (* args, ** kwargs) -.> STR args position parameter, a parameter tuple kwargs keywords, a dictionary
    braces {} placeholder i.e. by location match { n} represents the position parameter index value of n
    {} {} {} printing

    Access element
      "{0 [0]}. {0 [1]}". Format (( 'magedu', 'com')) magedu ',' com == 0 'magedu' = 0 [0]
    object properties accessible
      from Import namedtuple Collections
      Point = namedtuple ( 'Point', 'X, Y')
      P = Point (4,5)
      "0.x {{{}. {}}} 0.y." the format (P)

    Align
      '{: ^ 30}'. Format ( 'centered') centered
      '{: * ^ 30}' format ( 'centered') is centered and filled with *.

    Hex
      "int: {0: d} ; hex: {0: x}; oct: {0: o}; bin: {0: b}" format (42).
      Output is: 'int: 42; hex: . 2A; OCT: 52 is; bin: 101010 '
      . "int: {0: D}; hex: {0: #x is}; OCT: {0: #O}; bin: {0:} #b to" the format (42 is )
      output: 'int: 42; hex: Ox2a; oct: Oo52; bin: Ob101010'


XVI unordered set {} {} SET no mapping between the
      NUM = {1,2,3,4,5,5,6,5,4,3,1,1}
      NUM = {l, 2,3 , 4,5,6}
  to create a collection:
    setl XXXXXXXX} = {
    set2.set ([xxxxxxxxxx])


  Access to the collection:
    for the each in SET1:
    Print (the each, End = '')
  Operation:
    set1.add (num) increased num
    set1.remove (num) num deleted

  Immutable collection:
    set1.frozenset ({1,2,3,4})
    delete del set1

XVII function, i.e. parameter structure parameter
  classification: built-in functions, library functions,
    variable parameters: a parameter match any parameter
    variable position parameters: forming a collector tuple
    DEF the Add (the nums *): This parameter the nums you can take any argument to
      SUM = 0
      for X in the nums:
        SUM = X +
      return SUM
     the Add (l, 3,5) the Add (2,4,6) collecting a plurality of tuple argument

    variable key parameters: shape ** before with reference symbol represents a plurality of keywords acceptable parameters, the collected argument name and a value dict
    DEF showconfig (** kwargs):
      for K, V in kwargs.items ():
        Print ( '{} = { } '. format (k, v ))

    keywordonly-only parameter
      DEF Fun (* args, X, Y, ** kwargs);
        Print (X)
        Print (Y)
        Print (args)
        Print (kwargs)
      to define the legal
      fun (7,9, y = 5, x = 3 , A =. 1, B = 'Python')
      =>. 3
        . 5
        (7,9)
        { 'B': 'Python', 'A':. 1}

      def fun(*args,x):
        print(x)
        print(args)
      fun(3,5)   =>error
      fun(3,5,7)   =>error
      fun(3,5,x=7)   => x=7, 3,5=args

      Fn DEF (*, X, Y):
        Print (X, Y)
      Fn parameters (x = 5, y = 6 ) xy -only keyword must

    The variable parameters and parameter default values:
      DEF Fn (* args, X =. 5):
        Print (X)
        Print (args)
      Fn () == Fn (X =. 5) (). 5
      Fn (. 5) == (. 5, ). 5
      Fn (X =. 6) == (). 6

      def fn(y,*args,x=5):
        print('x={},y={}.format(x,y)')
        print(args)
      n(5)、fn(1,2,3,x=10)、

      Fn DEF (X =. 5, kwargs **):
        Print (. 'X = {}' the format (X))
        Print (kwargs)
      Fn () => X = {}. 5
      Fn (. 6) => X = {. 6 }
      Fn (X =. 7, Y =. 6) => X = {. 7 'Y':}. 6

  function parameters:
    the parameter rule general order: Common parameters, default parameters, variable position parameters, keyword-only parameter, variable keyword parameter
      DEF Fn (X, Y, Z =. 3, * args, m =. 4, n-, kwargs **):
        Print (X, Y, Z, m, n-)
        Print (args)
        Print (kwargs)
      Fn ( 1,2, n-=. 3) => 1,2,3,4,3 () {}
      Fn (1,2,10,11, T =. 7, n-=. 5) => 10 2. 4. 5. 1 (. 11 ,) { 't': 7 }

  Deconstruction parameters:
     DEF the Add (X, Y :)
        return X + Y
     the Add (4,5)
     T = (4,5)
       the Add (T [0], T [. 1])
       the Add (T *) deconstruction: Non-typical word * typical ** word

     = {D 'X':. 5, 'Y':}. 6
       the Add (D **)

  embedded functions and closures:
    internal functions can not have access to a global variable to change
      COUNT. 5 =
      DEF myfun ():
      Global COUNT
      COUNT = 10
      Print (COUNT)
      nuFun () => 10
      COUNT => 10

  闭包:
    def funX(x):
      def funY(y):
        return x+y
      return funY
    i = funX(8)
    i(5) => 13 // funX(8)(5)

  nonlocal: function may be moved inside the external function values of local variables
    DEF funX ():
      X =. 5
      DEF funy ():
        nonlocal X
        X X * =
        return X
      return funy
    funX () () => 25

  lambda create anonymous function:
    G lambda = X: 2. 1 * X +
    G (. 5) =>. 11

  filter (), Map ()
    filter has two parameters, the first parameter may be a function or None, if a function, then the data in the second iteration may each element parameter is calculated as a function of the return to True value
      If is None, then directly to the second parameter value is filtered out of the True
    Example: odd filter
    DEF oDD (X):
      return X 2%

    TEMP = filter (oDD, Range (10)) // List ( filter (the lambda X: X 2%, Range (10)))
    List (TEMP) => [1,3,5,7,9]

  map () maps two arguments, a function of adding an iterative sequence, the series of processing operation for each element as a parameter, known iterative sequence can be finished processing each element, and returns the new sequence

    list(map(lambda x: x * 2,range(10)) => [,2,4,6,8,10,12,14,16,18,20]


Eighteen, higher-order functions (functions as a return value, as a function of one or more parameters, tend to form closure)
  Y = F (G (X))
  DEF counter (Base):
    DEF inc is (= STEP. 1):
      nonlocal Base
      + = STEP Base
      return Base
    return inc is

  curried: original function accepts two arguments into a function that accepts a process parameter, a new function returns to the original function of the second parameter
    z = f (x, y ) => z = f (x ) (y)
  example: the Add DEF (X, Y):
          return X + Y
       Print (the Add (4,5))

    => DEF new_add (X):
           DEF Inner (Y):
            return Y + X
         return Inner

  Decorator *: essentially a higher-order functions,

Nineteen, file reading and writing
  statement: open ( 'path', 'mode', encoding = 'coding')
    path: "C: \\ path \\ data.txe '
        R'C: \ path \ data.txt'
    model : text: 'r' read 'w' write 'rw' read 'a' open, append
        a binary: '* B'
    F = open (r'E: \ pythonfile \ date.txt ',' R & lt ')
    F. read () # reading all pointers move to the end
    f.seek pointer at the beginning (0) # removable, re-read
    f.tell () # tell pointer position
    f.close () # close the file object
  read:
    F. read (n) # n-bit character information read
    f.readlines () # read all line information
    f.readline () # reads the next line

    Line in f.readlines for (): // for in Line F:
      Print (Line)

  query the current directory operation OS Import
            The os.getcwd ()
            the os.chdir (r'xxxxxx ') Change directory

  File written:
    F = Open ( 'path', 'mode', encoding = 'coding')
    f.write ( 'xxxxxxxxx')
    f.close ()
    f.writelines () # write-once multi-line
    f.flush ( ) # direct memory cache operation is displayed on the file

  Automatically release resources
    with open ( 'path', 'r', encoding = ' coding') AS F:
      for in Line F:
        Print (Line)

  the pickle module:
    Import the pickle
    my_list = [123,123.4, 'Hello', [another list ]]
    pickle_file = open (r'E: \ pythonfile \ my_list.pkl ',' WB ') writes binary
    pickle.dump (my_list, my_list.file) dump data storage method
    pickle_file.close ()

  open:
    Import the pickle
    pickle_file = open (r'E: \ pythonfile \ my_list.pkl ',' rb ') binary read
    my_list = pickle.load (pickle_file) load load data
    print (my_list)

Guess you like

Origin www.cnblogs.com/ygsworld/p/11101348.html