Python Basics Summary (constantly updated ....) )

Source: Internet
Author: User

An easy way to do this:
(1) Lambda x,y:x*y
(2) List1 = List (filter (lambda x:x%3 = = 0,range (100)))
Filter the first parameter is the filtering condition, the second is the content to be filtered
The return value is an object that has to be converted to another type
(3) Map:list1 = map (lambda x:x**2,[1,2,3,4,5])
The first one is the processing condition, the second is the sequence
The return value is an object
(4) [I-I in range] if i%2 ==0] Direct generate list

1. Indentation is the soul of Python
2. Get the variable type, type (), Isinstance (,)
3.S is a string

4. How can I get int rounded?
Int (x+0.5)
5.python3 supports Chinese variable names, but the source code is utf-8
6.python object 3 Features: Identity, type, value
7.python numeric type: Int,long,float,boolean, Complex (plural), Sequence type: dictionary, tuple, List
8. Typical python file structure:
(1) Starting line #/usr/bin/env/python
(2) Module document "This is a test module"
(3 Module Imports import OS
(4) (global) variable definition debug = True
(5) class definition (if any) classes Fooclass (Object):
Pass
(6) function definition: def test ():
( 7) Main program if name = " main "
9. Tuples immutable, list variable, dictionary variable
10.set function, remove repeating elements in collection, Li = Set (LIST2)
11. Two sets intersection: List1 & List2, gather: List1 | List2

  1. parent
    --_ init . PY
    --child
    --_ init . PY
    --a.py
    directory structure as above, if you want to reference a file, you can do this
    import Sys,os
    Sys.path.append (OS.GETCWD () + "\parent\child")
    from a import func
    13.os.walk (path)
    14.p,f = Os.path.split (spath) delimited directory and file name
    Drv,left = os.path.splitdrive (spath) separator letter and file name
    F,ext = Os.path.splitext (spath) Delimited file and extension
    15. Time Processing
    16. Three mesh operator: SM = x if x>y else y
    17.None for null type
    18.a=[1,2,3] b=[1,2,4] ID (a[1]) = = ID (b[1]) Tr UE
    19.python is a value-based memory management method, if the values of different variables are equal, their memory address ID (variable name) is equal
    20.dict.get (key,error) has the return value, NONE returns the hint
    21. List:
    Append (), Intsert (1, ' a '), extend (), sort (), reverse (), List[:],pop (), Del Li[0],copy (), clear ()
  2. [I for I in range] if I>10]
    23. Tuple: x = 1, x = 24.x = 2, 3 insert 5
    X[:2] + (' 5 ',) + x[2:]< Br>25.python built-in method:
    Divmod (10,2) returns the division and remainder of 10 to 2
    Pow (x, y, z) x, and if z exists, then%z
    Float,int,long,list,tuple,str, Dict converted to its type
    round round sum sum
    isinstance (1,int) whether the former belongs to the latter type
    ' I am {0}, I like {1} '. Format (' xy ', ' d ')
    Enumerate , returns an enumerable object (tuple)
    Set
    sorted sort
    All the elements in the collection are true and True
    Any (collection) has one element in the collection true to True
    CMP (x, y) x<y returns negative X ==y returns 0 X>y returns a positive number
    Next () returns the next element in the iteration object
    Reversed (range (10)) The inverse object
    sorted () Sorts the object, returns a new list
    Zip return tuple type
    x = [3]
    y = [4,5,6,7]
    Print (list (Zip (x, y))) [(1, 4), (2, 5), (6,)]
    Map:list1 = map (Lambda x:x**2,[1,2,3,4, 5])
    The first one is the processing condition, the second is the sequence
    The return value is Object
    Filter:list1 = List (filter (lambda x:x%3 = = 0,range))
    Filter The first parameter is the filter condition, the second is the content to be filtered
    The return value is an object, it has to be converted to a different type
    Help () returns the helper information for the object
    input reads the user input information
    Open Open file
    Exec Execute Dynamic statement block EXEC (' a=1+2 ')

26. Use the function name Doc to view the functions document
27. Closure function:
def fun1 (x):
def fun2 (y):
return x y
Return Fun2
28. String handling:
Capitalize () first uppercase
Title first lowercase
replace (' 1 ', ' 2 ') replace
Upper all caps
lower all lowercase
Swapcase uppercase and lowercase
Lstrip remove left space strip around Rstrip right space
Split
StartsWith to: Beginning EndsWith with. End
S.isalnum () All characters are numbers or letters, return Ture for True, otherwise return False.
S.isalpha () All characters are letters and return Ture for true, otherwise False is returned.
S.isdigit () All characters are numbers and return Ture for true, otherwise False is returned.
S.islower () All characters are lowercase, return Ture for true, or False.
S.isupper () All characters are uppercase and return Ture for true, otherwise False is returned.
S.istitle () All words are capitalized, return Ture true, or False.
S.isspace () All characters are white-space characters, return Ture for true, or False.
Replace
Find (' t ') has the return position, NONE returns 1
count (' t ') in the number of strings
29. Keyword: global variable outside the function, nonlocal internal function modifies the local variable of the external function
30.lambda function:
G = lambda x,y:x
y
G (2,3)---------6

31. Dictionary: D = {K:V,K1:V1}
Access: D[k],d.get (k)
Modify: d[k] = ' v2 '
Delete: del d[k] Delete a
D.clear () Clear all
del dict Delete dictionary
D.items () returns the (key, value) tuple
D.key ()
D.values ()
D.pop (k) Delete and return the value
x = {}
x = X.fromkeys ((+), ' a ')

  1. Set
    Features: unordered, cannot be indexed or performed slice operation
    Frozenset () non-modifiable collection
    Created:
    A = {-T}
    A = set (' Boy ')
    A = set ([' A ', ' B ', ' C ', ' d '])
    Compare: s = {2,5}
    S.difference (b)//Find a collection that exists in S, B does not exist, return the new value
    Add: S.add ()
    Delete: Discard S.discard (3)//delete non-existent element does not error
    Remove S.remove (3)//delete the non-existent element will error
    Pop s.pop ()//delete the last element and return the new value
    Take intersection: s = {+ = =} b = {2,5}
    S. Intersection (b)//Take intersection, assign to new value
    Judge: s = {---------] B = {2,5}
    S.isdisjoint (b)///Determine if there is no intersection (false with intersection, no intersection true)
    S.issubset (b)//To determine if S is a subset of B
    S.issuperset (b)//Determine if S is the parent collection of B
    : s = {= = {= = = {= = = = {= = = {] b = {2,5}
    S.union (b)//Fetch the set and assign a new value
    Update: s = { --------C = {2,5}
    S.update (b)
    Print (s) {1,2,3,5}
    33. File Handling:
    R Read-only r+ read/write w writable, presence overwrite w+ read/write, presence overwrite a append, non-existent create

    F.read () reads the entire contents of a file into a single str
    F.readline () reads a line
    F.readlines () reads all rows, and puts it into a list

    F.write () only writable string
    F.writelines () writable sequence

    When hints are garbled: add encoding= ' UTF-8 '
    Open (', ' w+ ', encoding= ' UTF-8 ')

  2. XLRD processing table
    Read
    #打开文件
    Workbook = Xlrd.open_workbook (R ' f:\ ')
    #获取所有sheet
    Workbook.sheet_names () Returns a list
    #根据sheet索引或者名称获取sheet内容
    Sheet2 = Workbook.sheet_by_index (1)
    Sheet2 = Workbook.sheet_by_name (' Sheet2 ')
    #获取sheet2的名称, number of rows, number of columns
    Sheet2.name,sheet2.nrows,sheet2.ncols
    #获取整行和整列的值 (array)
    rows = Sheet2.row_ VALUES (3) #第四行内容
    cols = sheet2.col_values (2) #第三列内容
    #获取单元格内容
    Sheet2.cell_value (1,0). Encode (' Utf-8 ')
    # Gets the data type of the cell contents
    Sheet2.cell (1,0). CType

    XLWT write file
    #创建工作簿
    F = xlwt. Workbook (encoding= ' utf-8 ')
    #创建第一个sheet
    Sheet1 = f.add_sheet (' Sheet1 ')
    #写数据, corresponding row and column values
    Sheet1.write (0,1, Label = ' This is the test ')
    #保存
    F.save (' xx.xlsx ')

  3. OS module
    Sample directory: Path = C:\Users\hwx518534\Desktop
    Os.name nt/posix
    os.getcwd () Get current working directory
    Os.curdir current directory
    Os.listdir (path) returns all files and directory names under the specified directory
    os.remove () Delete a file
    Os.rename () Rename
    Os.system () Execute system command
    Os.mkdir ()
    Os.rmdir ()
    Os.exit () terminates the current process
    Os.chdir () changes the current directory
    Os.walk () returns triples the first is the folder address the second is a list, All directory names under the current folder (excluding subdirectories)
    The third returned is list, which returns all files (not including subdirectories) under that folder

    Os.path module
    Sample directory: Path = C:\Users\hwx518534\ desktop\temp.py
    Os.path.abspath ( file ) absolute path to the current file
    Os.path.dirname () Gets the current file directory C:\Users\ Hwx518534\desktop
    Os.path.split () returns the directory name and file name of a path (' C:\Users\hwx518534\Desktop ', ' temp.py ')
    Os.path.isfile () Os.path.isdir detects whether the file or directory
    Os.path.exists () detects the path exists
    Os.path.getsize () Gets the file size (in bytes), and if the directory returns 0L,
    Os.path.splitext () detach file name with extension
    Os.path.join () connection directory with file name return value is path
    Os.path.basename () return file name

  4. _ Start variable meaning

    _XX represents a protected variable that cannot be imported through the from X Import x and can be accessed in objects and subclasses
    x represents a system-defined special variable
    __xx private members, only class objects themselves can access

  5. Time Module
    Time.time () The number of seconds since the epoch
    Time.ctime () Wed Jan 31 17:50:57 2018
    Time.localtime () time.struct_time (tm_year=2018, Tm_mon=1, tm_mday=31, tm_hour=9, tm_min=51, tm_sec=54, tm_wday=2, tm_ YDAY=31, tm_isdst=0)
    s = time.gmtime () s.tm_year---2018
    Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())
    2018-01-31 18:06:25
    38.shutil Module---Advanced files, folders, compression package processing module
    Shutil.copyfileobj (' xx.py ', ' R '), open (' X.txt ', ' W ')--Copy the file contents to another file
    Shutil.copyfile (' xx.py ', ' x1.py ')--copy files to another file
    Shutil.copystat (SRC,DST)--Copy state information only
    Shutil.copy (SRC,DST)--Copy files and status
    Shutil.copytree (' Folder1 ', ' Folder2 ')--Recursive Copy Folder
    Shutil.rmtree (' F1 ')--Recursive delete file (clip)
    Shutil.move (SRC,DST)--Renaming

Python Basics Summary (constantly updated ....) )

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.