Some magical [collection] of python, derivation, ternary expression, with as etc.

Used in their built-in functions

Function is as follows:

dir len str list tuple zip map reduce (now incorporated in functools)



Common base for the conversion

  1. Oct hex bin

lambda expressions

  1. May be a simple function of the code represents a more streamlined
  2. Format: lambda para1, para2, ...: Return Value:

Generating derivations

  1. Code amount can be reduced. For example, to generate a list 1 ~ 10:

  2. Direct call function you write will return the value of the deposit. (Familiar people would be so written: [i ** 2 for i in range (5)])

A triplet of expressions

  1. If else equivalent shorthand or deformed, so that a better code is simple. (Do not become 2 in a row smell? Of course not original simple)

  2. else if conditions do not meet the conditions for the implementation of conditions are met:

Magical fixed parameters, variable parameters, the default parameters

def func(name,age,sex = '男',*args,**kwds)

  1. Wherein the fixed parameter name and age, sex as the default parameters, * arg and ** kwds as variable parameters, ** kwds acceptable key input.
    ps: Some people might wonder why not show sex, in fact, because * args escaped, sex becomes a list.

  2. A separate default parameters:

with as a context-managers, such as opening a file

General are:

file = open("/log.txt")
data = file.read()
file.close()

Problems:

  1. You may forget to close the file;
  2. Abnormal file for reading occurs, no exception handling.
    Normal writing:
file = open("/log.txt")
try:
    data = file.read()
finally:
    file.close()

After use with as:

with open("/tmp/foo.txt") as file:
    data = file.read()

else else for execution after executing the equivalent for







Later update, the specific use of commonly used functions, to be continued ~~~


Guess you like

Origin www.cnblogs.com/yanshanbei/p/11954112.html