Pythonic is very python if translated into Chinese. Very + noun structure usage in China many, such as: Very Niang, very replace him, very CCTV and so on.
The following for the sake of brevity, we use p to denote the writing of pythonic, NP means non-pythonic, of course, this P-NP is not P-NP.
Why pursue Pythonic?
Compared to the np,p of concise, clear, elegant, most of the time the implementation of high efficiency, the less code will be more error-prone. I think good programmers in writing code, should pursue the correctness of the code, simplicity and readability, which is precisely the spirit of pythonic.
For programmers with experience in other programming languages (for example, myself), when writing Python code, it is more convenient and efficient to understand the pythonic, and the main reader of this article will be this group of programmers.
A sample of N of P and NP is given below, which is for readers ' reference and review.
Example of P vs. np
Chain comparison
P:
A = 3b = <= B <= a < #True
Np:
A = 3b = 1b >= 1 and b <= A and a < #True
P is the primary school students can read the grammar, simple direct code ~
Truth test
P:
Name = ' Tim ' langs = [' AS3 ', ' Lua ', ' C ']info = {' name ': ' Tim ', ' Sex ': ' Male ', ' age ': +} if Name and Langs and Info:
print (' All true! ') #All true!
Np:
If name! = "and Len (langs) > 0 and info! = {}: print (' All true! ') #All true!
In short, P's writing is for any object, directly determine its true and false, without written judgment conditions, so as to ensure correctness, but also to reduce the amount of code.
True and False Value table (remember the fake you can save a lot of code!) )
True and False
True False
Any non-empty string of null string ' '
Any non-0 digital number 0
Empty container for any non-empty container [] () {} set ()
Any other non-falsenone
String inversion
P:
def reverse_str (s): return s[::-1]
Np:
def reverse_str (s): t = ' for x in Xrange (Len (s) -1,-1,-1): t + = s[x] return t
P is simple to do, tested, and more efficient.
If used to detect palindrome, is a word input = = Input[::-1], how elegant!
Connection to a string list
P:
Strlist = ["Python", "is", "good"] res = ". Join (Strlist) #Python is good
Np:
res = "for S" in Strlist: res + = s + "#Python is good# there's a last extra space.
String.Join () is often used to concatenate strings in the list, which is efficient and does not make mistakes relative to np,p.
List sum, maximum, minimum, product
P:
Numlist = [1,2,3,4,5] sum = SUM (numlist) #sum = 15maxNum = Max (numlist) #maxNum = 5minNum = Min (numlist) #minNum = 1from operator Import Mulprod = reduce (Mul, numlist, 1) #prod = 120 default value 1 to prevent empty list error
Np:
sum = 0maxNum =-float (' inf ') Minnum = float (' inf ') prod = 1for num in numlist: if num > maxnum: maxnum = num
if num < minnum: minnum = num sum + = num prod *= num# sum = Maxnum = 5 Minnum = 1 PROD = 120
After a simple test, when the length of the numlist is 10000000, the sum of the list on my machine, p time 0.6s,np time consuming 1.3s, nearly twice times the gap. So don't build your own wheels.
List-derived
P:
L = [x*x for x in range] if x% 3 = = 0] #l = [0, 9, 36, 81]
Np:
L = []for x in range: if x% 3 = = 0: l.append (x*x) #l = [0, 9, 36, 81]
You see, using the list derivation of p, how easy and intuitive it is to build a new list!
Default values for Dictionaries
P:
DIC = {' name ': ' Tim ', ' age ': $ dic[' workage '] = dic.get (' Workage ', 0) + 1#dic = {' age ': $, ' workage ': 1, ' name ': ' Tim ' }
Np:
If ' Workage ' in dic: dic[' workage ' + = 1else: dic[' workage '] = 1#dic = {' age ': + ' workage ': 1, ' name ': ' Tim '}
The Get (Key,default) method of the dict is used to get the value of key in the dictionary, and if the key does not exist, the key is assigned the default value.
P compared to the NP of the wording less if...else ..., is really hate if...else ... The first choice of people!
For...else ... Statement
P:
For x in Xrange (1,5): if x = = 5: print ' Find 5 ' breakelse: print ' Can not ' find 5! ' #can not find 5!
Np:
find = FalseFor x in xrange (1,5): if x = = 5: find = True for print ' Find 5 ' breakif not find: print ' Can n OT Find 5! ' #can not find 5!
For...else ... The else part is used to handle cases where there is no interruption from the for loop. With it, we do not have to set the state variable to check if the For loop has break out, simple and convenient.
Substitution of ternary characters
P:
A = 3 b = 2 if a > 2 else 1#b = 2
Np:
If a > 2: b = 2else: b = 1#b = 2
If you have C programming experience, you will be looking for a? Alternative to B:C. You may find A and B or C look good, but B = a > 1 and False or True returns True, and the actual intent should return False.
Using B = False if a > 1 else true returns False correctly, so it is an authentic ternary substitute.
Enumerate
P:
Array = [1, 2, 3, 4, 5] for I, E in Enumerate (array,0): print I, e#0 1#1 2#2 3#3 4#4 5
Np:
For i in Xrange (len (array)): print I, Array[i] #0 1#1 2#2 3#3 4#4 5
Using enumerate, you can remove indexes and values at once, avoid using indexes to take values, and the second parameter of enumerate can adjust the starting position of index subscript, default is 0.
Create a key value pair using zip
P:
Keys = [' name ', ' Sex ', ' age ']values = [' Tim ', ' Male ', [+] dic = dict (Zip (keys, values)) #{' age ': ", ' name ': ' Tim ', ' Se X ': ' Male '}
Np:
DIC = {}for i,e in Enumerate (keys): dic[e] = values[i]#{' age ': $, ' Name ': ' Tim ', ' Sex ': ' Male '}
The Zip method returns a tuple, which is used to create a key-value pair, which is straightforward.