Python Coding Summary

Source: Internet
Author: User
Tags extend integer division shallow copy throw exception


1. Map, filter, reduce
1) Map (func, Input_list)
Apply the function to each element on the input list, such as:
Input_list = [1, 2, 3, 4, 5]


def pow_elem (x):
"""
To do a exponentiation on X
:p Aram x:
: return:
"""
return x * x


def multi_x_y (x, y):
return x * y


Print map (Pow_elem, input_list) # output:[1, 4, 9, 16, 25]

Print map (multi_x_y, Input_list, input_list) # output:[1, 4, 9, 16, 25]

2) filter (Func_or_none, sequence)
Filtering out the values in sequence that satisfy the function return true, forming a new sequence return, such as:
def is_odd (x):
"""
Determine if x is an odd number
:p Aram x:
: return:
"""
Return True if x% 2 > 0 Else False

Print filter (is_odd, input_list) # output: [1, 3, 5]

3) reduce (function, sequence)
The reduce () function receives a parameter similar to map (), a function f, a list, but behaves differently from map (), and reduce () the incoming function f must receive two parameters, and reduce () calls function f repeatedly on each element of the list and returns the final result value. For example: reduce (lambda x, Y:x+y, [1, 2, 3, 4, 5]) is equivalent to (((((1+2) +3) +4) +5)
Print reduce (lambda x, y:x * y, input_list) # output:120

2, ternary operation
The following two types of notation are equivalent:
"Yes" if 2==2 else "No"
("No", "Yes") [2==2]
That
1) condition_is_true If condition else condition_is_false
2) (If_test_is_false, if_test_is_true) [test]
1) and 2) can achieve ternary operations, but 2) is relatively rare, and not too elegant, and 2) is not a short-circuit operation, as follows:
5 if True else 5/0 # Output:5
(1/0, 5) [True] # throw exception-> Zerodivisionerror:integer division or modulo by zero

3, the decorative device
1) In Python, we can define functions within functions and invoke them, such as:
def hi (name= "Patty"):
Print ("Now is inside the hi () function")

def greet ():
Return "Now is in the greet () function"

Def welcome ():
Return "Now is in the Welcome () function"

Print (greet ())
Print (Welcome ())
Print ("Now is back in the Hi () function")
The output is:
Now is inside the hi () function
Now is in the greet () function
Now is in the welcome () function
Now is back in the Hi () function

2) You can also return an intrinsic function and invoke it using an external function, such as:
def hi (name= "Patty"):
def greet ():
Return "Now is in the greet () function"

Def welcome ():
Return "Now is in the Welcome () function"

return greet if name = = ' Patty ' else welcome


Print hi () # <function greet at 0x109379a28>
Print hi () () # Now is in the greet () function
In the above code, the HI () call returns a function object, which can be judged from the If/else statement that the greet () function is returned, and when we call Hi () (), the intrinsic function greet () is actually called.

3) Pass the function as an argument to another function, such as:
def hi ():
Return "Hi patty!"

def Dosomethingbeforehi (func):
Print ("I am doing some boring work before executing hi ()")
Print (func ())

Dosomethingbeforehi (HI)
Output Result:
I am doing some boring work before executing hi ()
Hi patty!
At this point, we have implemented a simple adorner, before calling the Hi () function, first output a line, the actual application may be some preprocessing operations. In fact, the function of adorners is to add some common functions before and after your core logic executes.

4) The realization of the simple decorative device
def a_new_decorator (A_func):

Def wrapthefunction ():
Print ("I am doing some boring work before executing a_func ()")

A_func () # Call the This function

Print ("I am doing some boring work after executing a_func ()")

Return wrapthefunction

Def a_function_requiring_decoration ():
Print ("I am the function which needs some decoration to remove my foul smell")

A_function_requiring_decoration ()
#outputs: "I am the function which needs some decoration to remove my foul smell"

A_function_requiring_decoration = A_new_decorator (a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapthefunction ()

A_function_requiring_decoration ()
# I am doing some boring work before executing a_func ()
# I AM the function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func ()

5) Annotation Form
@a_new_decorator
Def b_function_requiring_decoration ():
Print ("I am the another function which needs some decoration to remove my foul smell")

B_function_requiring_decoration ()
# I am doing some boring work before executing a_func ()
# I AM the another function which needs some decoration to remove my foul smell
# I am doing some boring work after executing a_func ()
Here @a_new_decorator is equivalent to A_new_decorator (b_function_requiring_decoration)

6) Get Name
For the a_function_requiring_decoration in 4, we printed print (a_function_requiring_decoration.__name__) to get the result wrapthefunction , and what we actually want to get is the name of the A_function_requiring_decoration function that a_func corresponds to, and Python gives us wraps to solve the problem.
From Functools Import Wraps
def a_new_decorator (A_func):
@wraps (A_func)
Def wrapthefunction ():
Print ("I am doing some boring work before executing a_func ()")

A_func ()

Print ("I am doing some boring work after executing a_func ()")

Return wrapthefunction

7) Some application scenarios of adorners
User authentication
Def Requires_auth (f):
@wraps (f)
def decorated (*args, **kwargs):
Auth = {"username": "Patty", "Password": "123456"}
If not Check_auth (auth[' username '), auth[' password ']):
Authenticate ()
Return f (*args, **kwargs)

def check_auth (username, password):
Print "Starting check auth ..."
Return True if (username = = ' patty ' and password = = ' 123456 ') Else False


Def authenticate ():
Print "Already Authenticate"
return decorated

@requires_auth
Def welcome ():
Return "Welcome patty!"

Print welcome ()

Log records
def logit (func):
@wraps (func)
def with_logging (*args, **kwargs):
Print (func.__name__ + "was called")
return func (*args, **kwargs)
Return with_logging

@logit
def addition_func (x):
"" "Do some math." "
return x + X


result = Addition_func (4)
Will print: Addition_func was called

8) Adorner with parameters
From Functools Import Wraps

def logit (logfile= ' Out.log '):
def logging_decorator (func):
@wraps (func)
def wrapped_function (*args, **kwargs):
log_string = func.__name__ + "was called"
Print (log_string)
# Open the logfile and append
With open (logfile, ' a ') as Opened_file:
# Now we log to the specified logfile
Opened_file.write (log_string + ' \ n ')
Return wrapped_function
Return Logging_decorator

@logit ()
Def myfunc1 ():
Pass

MYFUNC1 ()
# output:myfunc1 was called
# A file called Out.log now exists, with the above string

@logit (logfile= ' Func2.log ')
Def MYFUNC2 ():
Pass

MYFUNC2 ()

9) Use class as Adorner
Import OS
Class Logit (object):
def __init__ (self, log_file):
Self.log_file = Log_file

def __call__ (Self, func):
With open (Self.log_file, ' a ') as Fout:
Log_msg = func.__name__ + "was called"
Fout.write (LOG_MSG)
Fout.write (OS.LINESEP)
# Now, send a notification
Self.notify ()

def notify (self):
# logit only logs, no more
Pass

Class Emaillogit (Logit):
‘‘‘
A logit implementation for sending emails to admins
When the function is called.
‘‘‘
def __init__ (self, log_file, email= ' [email protected] '):
Self.email = Email
Super (Emaillogit, self). __init__ (Log_file)

def notify (self):
# Send an e-mail to Self.email
# would is not being implemented here
With open (Self.log_file, ' a ') as F:
F.write ("Do Something ....")
F.write (OS.LINESEP)
F.write ("Email has send to" + Self.email)
F.write (OS.LINESEP)


@Logit ("Log1.txt")
Def myfunc3 ():
Pass

@EmailLogit ("Log2.txt")
Def MYFUNC4 ():
Pass
With classes as adorners, our code looks more concise and can be inherited to personalize and reuse functionality.

4. Variable type
mutable types in Python include lists and dictionaries, elements of which can be changed, such as
>>> foo = [' Hi ']
>>> foo + = [' Patty ']
>>> Foo
[' Hi ', ' Patty ']
>>> foo[0]= ' Hello '
>>> Foo
[' Hello ', ' Patty ']

>>> fdict = {"Name": "Patty"}
>>> fdict.update ({"Age": "23"})
>>> fdict
{' Age ': ' + ', ' name ': ' Patty '}
>>> fdict.update ({"Age": "25"})
>>> fdict
{' Age ': ' + ', ' name ': ' Patty '}

In a method, if the passed-in parameter takes a mutable type and assigns a default value, be aware that the following occurs:
>>> def add_to (num, target=[]):
... target.append (num)
... Return target
...
>>> add_to (1)
[1]
>>> add_to (2)
[1, 2]
>>> add_to (3)
[1, 2, 3]
this is because , the default parameter is evaluated when the method is defined, rather than once per call. Therefore, in order to avoid this situation, when we expect each method to be called, when a new empty list is calculated, you can take the following wording:
>>> def add_to (num, target=none):
... if target is None:
... target = []
... target.append (num)
... return target
...
>>> add_to (1)
[1]
>>> add_to (2)
[2]

5, shallow copy and deep copy
In Python, there is a difference between the assignment of an object and the copy (deep/shallow copy), which can produce unexpected results if used without notice.
1) The default in Python is shallow copy mode
>>> foo = [' Hi ']
>>> bar = foo
>>> ID (foo)
4458211232
>>> ID (BAR)
4458211232
>>> bar.append ("Patty")
>>> Bar
[' Hi ', ' Patty ']
>>> Foo
[' Hi ', ' Patty ']
NOTE: the ID (foo) ==id (bar) indicates that Foo and bar refer to the same object, and when the list is append by the bar reference, the output of Foo is consistent with bar because it points to the same memory space.

2) deep copy
>>> Foo
[' Hi ', {' Age ': ' ' name ': ' Patty '}]
>>> Import Copy
>>> slow = copy.deepcopy (foo)
>>> Slow
[' Hi ', {' Age ': ' ' name ': ' Patty '}]
>>> slow[0]= ' Hello '
>>> Slow
[' Hello ', {' Age ': ' ' name ': ' Patty '}]
>>> Foo
[' Hi ', {' Age ': ' ' name ': ' Patty '}]
Note: Since slow is a deep copy of Foo, it actually opens up a new space in memory and copies the contents of the Foo object to the new memory space, so when the update operation is made to the content referenced by the slow, the change is only reflected on the slow object's reference. The content referenced by the Foo object does not change.

6, set Collection
1) defaultdict
For normal dict, if a nonexistent key is obtained, a keyerror error is thrown, as follows:
Some_dict = {}
some_dict[' colours ' [' favourite '] = "yellow"
# raises Keyerror: ' Colours '
But through defaultdict, we can avoid this situation, as follows:
Import Collections
Import JSON
Tree = lambda:collections.defaultdict (tree)
Some_dict = Tree ()
some_dict[' colours ' [' favourite '] = "yellow"
Print Json.dumps (some_dict)
# Works Fine, output: {"Colours": {"favourite": "Yellow"}}

2) ordereddict
Ordereddict can print the output dictionary in the order that we define the dictionary, and changing the value of value does not change the order of the key, but when the key is deleted and reinserted, the key is reordered to the end of the Dict.
From collections Import Ordereddict

Colours = Ordereddict (["Red", 198), ("Green", 160)])
For key, value in Colours.items ():
Print (key, value)

3) Counter
With counter, you can count the occurrences of a particular item, such as:
From collections Import Counter

Colours = (
(' Yasoob ', ' Yellow '),
(' Ali ', ' Blue '),
(' Arham ', ' Green '),
(' Ali ', ' Black '),
(' Yasoob ', ' Red '),
(' Ahmed ', ' Silver '),
)

Favs = Counter (name for name, colour in colours)
Print (favs)
# Counter ({' Yasoob ': 2, ' Ali ': 2, ' Arham ': 1, ' Ahmed ': 1})

4) Deque
Deque is a double-ended queue that can be inserted and deleted at the end of the tail, as follows:
From collections Import Deque
Queue_d = Deque ()
Queue_d.append (1)
Queue_d.append (2)
Print Queue_d # deque ([1, 2])
Queue_d.appendleft (3)
Print Queue_d # deque ([3, 1, 2])

Queue_d.pop ()
Print Queue_d # deque ([3, 1])
Queue_d.popleft ()
Print Queue_d # deque ([1])

Deque can set the maximum length of a queue, and when the number of elements exceeds the maximum length, the corresponding number of elements is removed from the current inverse direction with the insertion direction, as follows:
Queue_c = Deque (maxlen=5, Iterable=[2, 4, 6])
Queue_c.extend ([7, 8])
Print Queue_c # deque ([2, 4, 6, 7, 8], maxlen=5)
Queue_c.extend ([10, 12])
Print (Queue_c) # deque ([6, 7, 8, ten, A], maxlen=5)
Queue_c.extendleft ([18])
Print (Queue_c) # deque ([6, 7, 8, ten], maxlen=5)

5) Nametuple
A tuple is an immutable list and cannot be re-assigned to elements in a tuple, we can only access elements in a tuple by index. Nametuple can be seen as an immutable dictionary that accesses elements in a tuple by name. Such as:
From collections Import Namedtuple

Animal = namedtuple (' Animal ', ' name Age type ')
Perry = Animal (name= "Perry", Age=31, type= "cat")

Print (Perry)
# Output:animal (name= ' Perry ', age=31, type= ' cat ')

Print (Perry.name)
# Output: ' Perry '

Print (Perry[0])
# Output: ' Perry '

Print (Perry._asdict ())
# output:ordereddict ([' Name ', ' Perry '), (' Age ', ' + '), (' type ', ' cat ')])

7, Object introspection
1) dir: Enumerate all methods of this object
2) Type: return types of objects
3) ID: Returns the ID of the object

8. Generator
1) List
>>> squared = [x**2 for x in range (10)]
>>> Squared
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2) Dict
{v:k for k, V in Some_dict.items ()}
3) Set
>>> squared = {x**2 for x in range (10)}
>>> Squared
Set ([0, 1, 4, 81, 64, 9, 16, 49, 25, 36])

9. Exception Handling
Try
Print (' I am sure no exception is going to occur! ')
Except Exception:
Print (' exception ')
Else
# any code this should only run if no exception occurs in the try,
# but for which exceptions should isn't be caught
Print (' This would only run if no exception occurs. and an error here '
' would not being caught. ')
Finally
Print (' This would is printed in every case. ')

# output:i am sure no exception is going to occur!
# This would only run if no exception occurs.
# This would is printed in every case.
The statement in else is executed before finally.

10. Built-in method
A_list = [[1, 2], [3, 4], [5, 6]]
Print (List (itertools.chain.from_iterable (a_list)))
# Output: [1, 2, 3, 4, 5, 6]

# or
Print (List (Itertools.chain (*a_list)))
# Output: [1, 2, 3, 4, 5, 6]


Class A (object):
def __init__ (self, A, B, C, D, E, f):
Self.__dict__.update ({k:v for K, V in Locals (). Items () if k! = ' self '})

11. For-else Statement
There are two normal ways to end a For statement: One is to break out of a loop if a particular condition is met, and the other is to end all the conditions in the loop. The Else statement in For-else is executed only if all conditions have been judged and then the for loop ends normally, as follows:
For x in range (1, 10, 2):
If x% 2 = = 0:
Print "Found even of%d"%x
Break
Else
Print "Not foud even"
# Output:not Foud Even

12. Compatible with Python and Python
1) Use the __future__ module to refer to Python's modules in Python's environment
2) compatible Module import method
Try
Import urllib.request as Urllib_request # for Python 3
Except Importerror:
Import Urllib2 as Urllib_request # for Python 2

Reference:http://book.pythontips.com/en/latest/index.html

Python Coding Summary

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.