Reprint: https://mp.weixin.qq.com/s?timestamp=1498528588&src=3&ver=1&signature= dffeofpxy44obcmo3ymbllgt5ifzbfaushvog4m*jyf1w-glidzd7vopwjn5f36dbvcabji33dkfxw6i-h*f7hvyz-wkid* cwqapnqknczu-d1o0fnl7h5dnb0habcbojv0c7i0*vmikezhgafowkbtf*liov3dqxtjldfqi-lg=
One of the biggest advantages of the Python language is the simplicity of the syntax and the good code, like pseudocode, that is clean, neat, and straightforward. But sometimes we write code, especially Python beginners, often or according to other language thinking habits to write, that way not only run slowly, the code read up also, give people a kind of muddy
Feeling, after a period of time even oneself also can not understand.
Hall Abelson, author of the construction and interpretation of computer programs, said, "Programs must is written for people to read, and just incidentally for machines to execute."
To write Pythonic (elegant, authentic, neat) code, but also to observe those Daniel code more often, Github has a lot of very good source code is worth reading, such as: Requests, flask, Tornado, I enumerate some common pythonic wording, Hope to bring you a little enlightenment.
1. Variable Exchange
When swapping the values of two variables in most programming languages, you have to introduce a temporary variable:
>>> a = 1
>>> B = 2
>>> tmp = a
>>> a = b
>>> B = tmp
Pythonic
>>> A, B = B, a
2. Looping through interval elements
For i in [0, 1, 2, 3, 4, 5]:
(print i)
# or
For i in range(6):
(print i)
Pythonic
For i in xrange(6):
(print i)
Xrange returns the Generator object, the generator is more memory-saving than the list, but it is important to note that Xrange is python2 in the notation, Python3 only the Range method, features and xrange are the same.
3. Collection traversal with index position
When iterating through a collection, if you need to use the index position to the collection, it is common to iterate over the collection without index information in the normal way:
Colors = [' Red ', ' green ', ' Blue ', ' yellow ']
For i in range(len(colors)):
print (i, '---> ', colors[i])
Pythonic
for i, color in enumerate(colors):
print (i, '---> ', color)
4. String connection
When strings are concatenated, the normal way is to use the + operation
Names = [' Raymond ', ' Rachel ', ' Matthew ', ' Roger ',
' Betty ', ' Melissa ', ' Judith ', ' Charlie ']
s = names[0]
For name in names[1:]:
s + = ', ' + name
Print (s)
Pythonic
Print (', '. Join (names))
Join is a more efficient way to concatenate strings, and each time A + operation is performed, it causes a new string object to be generated in memory, traversing 8 times with 8 string generation, resulting in unnecessary memory waste. The whole process of using the Join method will only produce a string object.
5. Open/Close files
When performing a file operation, you must not forget the last action is to close the file, even if the error is close. The normal way is to call the Close method in the finnally block.
F = open(' data.txt ')
Try:
Data = f. Read()
Finally:
f. Close()
Pythonic
With open(' data.txt ') as F:
Data = f. Read()
With the WITH statement, the file object is closed automatically after the file operation is performed.
6. List Deduction formula
When you can solve a problem concisely with a single line of code, never use two lines, such as
Result = []
For i in range(ten):
s = i*2
result. Append(s)
Pythonic
[I*2 for I in Xrange (10)]
Similar to this, there are generator expressions, dictionary derivation, are very pythonic.
7, the use of decorative device
Decorators can pull out code unrelated to the business logic to keep the code clean and refreshing, and the adorner can be reused in multiple places. For example, a crawler Web page function, if the URL has been crawled directly from the cache, or crawl down to add to the cache, prevent subsequent repeated crawls.
def web_lookup(url, saved={}):
if url in saved:
return saved[URL]
page = urllib. Urlopen(url). Read()
saved[url] = page
return page
Pythonic
Import urllib #py2
#import urllib.request as Urllib # py3
def Cache(func):
Saved = {}
def wrapper(URL):
if url in saved:
return saved[URL]
else:
page = func(url)
saved[url] = page
return page
return wrapper
def web_lookup(url):
return urllib. Urlopen(url). Read()
Using adorners to write code on the surface feels more code, but it leaves out the cache-related logic and can give more function calls, so the total code is much less, and the business approach looks concise.
8. Rational use of the list
A list object is a data structure that is more efficient than an update operation, such as deleting an element and inserting an element when the execution is inefficient because the remaining elements are moved
Names = [' Raymond ', ' Rachel ', ' Matthew ', ' Roger ',
' Betty ', ' Melissa ', ' Judith ', ' Charlie ']
Names. Pop(0)
Names. Insert(0, ' Mark ')
Pythonic
From collections import deque
Names = deque([' Raymond ', ' Rachel ', ' Matthew ', ' Roger ',
' Betty ', ' Melissa ', ' Judith ', ' Charlie '])
Names. Popleft()
Names. Appendleft(' Mark ')
Deque is a two-way queue data structure that removes elements and inserts elements quickly
9. Sequence Unpacking
P = ' Vttalk ', ' female ', ' [email protected] '
Name = P[0]
Gender = p[1]
Age = p[2]
email = P[3]
Pythonic
Name, gender, age, email = p
10. Traverse the dictionary key and value
Method one speed is not so fast, because each iteration of the time to re-hash to find the key corresponding to the value.
Method two encounters a dictionary very large time, will cause the memory consumption increases more than one times
# method One
For K in d:
print (k, '---> ', d[K])
# method Two
for K, v in d. Items():
print (k, '---> ', v)
Pythonic
for K, v in d. Iteritems():
print (k, '---> ', v)
Iteritems returns an iterator object that saves more memory, but there is no such method in Python3, only the items method, equivalent to Iteritems.
Of course, there are many pythonic writing, not listed here, there may be a second period, welcome message. Feel Good Zan a bar (^o^)/
The code is more elegant (Python version) (reproduced)