Examples of some practical pythonic syntax and pythonic syntax
Preface
Python is a simple and elegant language. It may be too simple to use it without having to spend too much time learning. In fact, there are some good features in python, it can greatly simplify the logic of your code and improve the readability of the Code.
The so-called Pythonic is a Python code with extremely Python characteristics (code significantly different from other languages)
For pythonic, you can open python on The terminal and input import this to see what The output is. this is Tim Peters's "The Zen of Python", this poetic poem outlines the design philosophy of python. These ideas are basically common in all languages.
Beautiful is better than uugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors shoshould never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There shoshould be one-and preferably only one-obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than * right * now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea-let's do more of those!
Use the generator yield
Generator is a very useful syntax feature in python, but it is also the most easily overlooked, probably because list can be used in most places where generators can be used.
A generator can be simply understood as a function. Each time a yield statement is executed, a value is returned. By constantly calling this function, all values can be obtained, these values can constitute an equivalent list, but different from the list, these values are constantly calculated, and the list is computed at the beginning, this is the idea of lazy evaluation. This feature is very useful in scenarios with a particularly large amount of data, such as Big Data Processing. If you cannot load all files at a time, you can use the generator to process one row without worrying about memory overflow.
def fibonacci(): num0 = 0 num1 = 1 for i in range(10): num2 = num0 + num1 yield num2 num0 = num1 num1 = num2for i in fibonacci(): print(i)
Use the else clause to simplify loops and exceptions
If/else has been used, but in python, else can also be used in loops and exceptions.
# Pythonic syntax for cc in ['U', 'id', 'jp ', 'us']: if cc = 'cn': breakelse: print ('no cn') # General Syntax: no_cn = Truefor cc in ['uk ', 'id', 'jp', 'us']: if cc = 'cn': no_cn = False breakif no_cn: print ('no cn ')
The meaning of putting else in the loop is that if the loop is completely traversed and break is not executed, the else clause is executed.
# Pythonic try: db.exe cute ('Update table SET xx = xx WHERE yy = yy') failed t DBError: db. rollback () else: db. commit () # general syntax has_error = Falsetry: db.exe cute ('Update table SET xx = xx WHERE yy = yy') failed t DBError: db. rollback () has_error = Trueif not has_error: db. commit ()
Put else in the exception to indicate the operation to be executed if no exception occurs
Use the with clause to automatically manage resources
As we all know, open files need to be closed after they are used up. Otherwise, resource leakage may occur, but they are often forgotten to be closed during actual programming, especially in complicated logic scenarios, in addition, python has an elegant solution, that is, the with clause.
# Pythonic with open ('pythonic. py ') as fp: for line in fp: print (line [:-1]) # general formula fp = open ('pythonic. py ') for line in fp: print (line [:-1]) fp. close ()
After using the with as statement, you do not need to manually callfp.close()
The file will be automatically closed after the scope ends. The complete execution is as follows:
- Call
open('pythonic.py')
, Returns an object obj,
- Call
obj.__enter__()
Method. The returned value is assigned to fp.
- Execute the code block in
- Run
obj.__exit__()
- If an exception occurs in this process, send the exception
obj.__exit__()
, Ifobj.__exit__()
If the return value is False, an exception is thrown. If the return value is True, the exception is suspended and the program continues to run.
List derivation and generator expression
List Derivation
[Expr for iter_var in iterable if cond_expr]
Generator expression
(Expr for iter_var in iterable if cond_expr)
List derivation and generator expressions provide a very simple and efficient way to create a list or iterator.
# Pythonic syntax squares = [x * x for x in range (10)] # general syntax squares = [] for x in range (10): squares. append (x * x)
Traverse map with items
There are many ways to traverse map in python. We recommend that you use the items () function when colleagues need to use key and value.
m = {'one': 1, 'two': 2, 'three': 3}for k, v in m.items(): print(k, v)for k, v in sorted(m.items()): print(k, v)
Reference
Google python language specification: http://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules/
Writing high-quality code: 91 suggestions for improving Python programs
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.