8 tips for efficient Python Programming

Source: Internet
Author: User

8 tips for efficient Python Programming
As a dynamic language, Python provides a lot of syntactic sugar to help us implement complex functions with very short code. On the other hand, Python has a long history and has accumulated a large number of efficient and easy-to-use libraries. Basically, common tasks have corresponding tool libraries. Using the Python language features, we can write Pythonic code. Next we will discuss how to write efficient Python code.
1. Use lambda expressionsLambda: This is an interesting syntax supported by Python. It allows you to quickly define the smallest function of a single row. Similar to Macros in C, these lambda functions are borrowed from LISP, it can be used in any function:
>>> G = lambda x: x * 2
>>> G (3)
6
>>> (Lambda x: x * 2) (3) 6

2. Use filter to filter list and dict(Function, sequence): Execute function (item) in sequence for items in sequence, and combine items whose execution result is True into a List/String/Tuple (depending on the sequence type). Return: >>> def f (x): return x % 2! = 0 and x % 3! = 0
>>> Filter (f, range (2, 25 ))
[5, 7, 11, 13, 17, 19, 23]
>>> Def f (x): return x! = 'A'
>>> Filter (f, abcdef)
'Bcdef'
3. Powerful map reduce FunctionsMap (function, sequence): Execute function (item) in sequence for items in sequence. See the execution result to form a List and return:
>>> Def cube (x): return x * x
>>> Map (cube, range (1, 11 ))
[1, 8, 27, 64,125,216,343,512,729,100 0]
>>> Def cube (x): return x + x
...
>>> Map (cube, abcde)
['A', 'bb ', 'cc', 'dd', 'ee']
In addition, map also supports multiple sequence, which requires that the function also supports the corresponding number of parameter inputs:
>>> Def add (x, y): return x + y
>>> Map (add, range (8), range (8 ))
[0, 2, 4, 6, 8, 10, 12, 14]

Reduce (function, sequence, starting_value): Calls the function sequentially for items in sequence. If starting_value exists, it can also be called as an initial value. For example, it can be used to sum the List:
>>> Def add (x, y): return x + y
>>> Reduce (add, range (1, 11 ))
55 (Note: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10)


4. Do not use temporary variables for variable exchange> a = 1> B = 2> a, B = B,
5. flexible use of the generator yield to make the code more concise and elegant
The generator provides a more convenient way to generate an iterator. The code is more concise and elegant. It makes full use of the latency evaluation feature and generates corresponding elements only when needed, instead of generating all elements at a time, saving memory and improving efficiency makes it easier for the coprocessor to implement. The coprocessor has multiple near-entry points and can resume suspended functions. In fact, python coroutine libraries such as greenlet are implemented based on yield. Use the Fibonacci function written by yield.

>>> def fib(n):...     a = b = 1...     for i in range(n):...             yield a...             a,b = b, a+b...>>> c = fib(10)>>> c.next()1>>> c.next()1>>> c.next()2>>> c.next()3>>> c.next()5



6. flexible use of list, set, deque, and array to optimize performance
7. flexible use of sort, sorted sorting sort can only sort the list, without changing the original list sorted can sort any iterator, such as the dictionary dict, tuples, and multi-dimensional list.
>>> from operator import itemgetter>>> gameresult = [['jim',96,'A'],['Eddy',99,'A'],['Cindy',87,'B'], ['Lucy', 76, 'C']]>>> sorted(gameresult, key=itemgetter(2,1))[['jim', 96, 'A'], ['Eddy', 99, 'A'], ['Cindy', 87, 'B'], ['Lucy', 76, 'C']]


8. The python standard library is used. This library contains too many contents. Common libraries such as requests, jsonlib, pandas, and argparse are not expanded.

 

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.