How to make your Python code more pythonic? If pythonic is translated into Chinese, it is very python. Many + terms are used in China, such as Niang, Guozu, and CCTV. ·
For the sake of simplicity, we use P to represent pythonic writing, NP to represent non-pythonic writing, of course, this P-NP is not P-NP.
Why the pursuit of pythonic?
Compared with NP, P is concise, clear, and elegant. In most cases, the execution efficiency is high. the less code, the less error prone. I think a good programmer should pursue the correctness, simplicity, and readability of the code when writing code, which is precisely the spirit of pythonic.
For programmers who have experience in other programming languages and are initially involved in Python (such as myself), it is more convenient and efficient to realize the pythonic writing method when writing Python code, the main readers of this article will also be programmers.
The following describes n examples of P and NP for your reference.
Example of P vs. NP
Chain comparison
P:
a = 3b = 11 <= b <= a < 10 #True
NP:
a = 3b = 1b >= 1 and b <= a and a < 10 #True
P is a syntax that elementary school students can understand. it is simple and straightforward to save code ~
True Value test
P:
name = 'Tim'langs = ['AS3', 'Lua', 'C']info = {'name': 'Tim', 'sex': 'Male', 'age':23 } 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 is written to determine the true and false of any object without writing judgment conditions. This ensures correctness and reduces the amount of code.
Real value table (you can save a lot of code if you remember false !)
True or false
True False
Any non-empty string null string''
Any number other than 0, 0
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 easy to write and tested to improve efficiency.
If it is used to detect input, it is a sentence of input = input [:-1]. how elegant!
String list connection
P:
strList = ["Python", "is", "good"] res = ' '.join(strList) #Python is good
NP:
Res = ''for s in strList: res + = s +'' # Python is good # There is an extra space at the end.
String. join () is often used to connect strings in the list. compared with NP, P is very efficient and will not make mistakes.
List summation, maximum value, minimum value, product
P:
NumList = [1, 2, 3, 4, 5] sum = sum (numList) # sum = 15 maxNum = max (numList) # maxNum = 5 minNum = min (numList) # minNum = 1 from operator import mulprod = reduce (mul, numList, 1) # prod = 120 default value 1 report an error in the anti-DDoS list
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 = 15 maxNum = 5 minNum = 1 prod = 120
After a simple test, when the numList length is 10000000, sum the list on my machine, P takes 0.6 s, NP takes 1.3 s, nearly two times the gap. So don't create your own wheels.
List derivation
P:
l = [x*x for x in range(10) if x % 3 == 0]#l = [0, 9, 36, 81]
NP:
l = []for x in range(10): if x % 3 == 0: l.append(x*x)#l = [0, 9, 36, 81]
You can see how simple and intuitive it is to build a new list using the list derivation of P!
Default value of dictionary
P:
dic = {'name':'Tim', 'age':23} dic['workage'] = dic.get('workage',0) + 1#dic = {'age': 23, 'workage': 1, 'name': 'Tim'}
NP:
if 'workage' in dic: dic['workage'] += 1else: dic['workage'] = 1#dic = {'age': 23, 'workage': 1, 'name': 'Tim'}
The get (key, default) method of dict is used to obtain the value of the key in the dictionary. if this key does not exist, the key is assigned to the default value.
P is less than if... else... than NP, which is the first choice for people who hate if... else!
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 print 'find 5' breakif not find: print 'can not find 5!'#can not find 5!
The else section of for... else... is used to handle situations where the for loop is not interrupted. With it, we do not need to set the status variable to check whether the for loop has a break, which is simple and convenient.
Substitution of ternary operators
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 look for? B: replacement of C. You may find that A and B or C looks good, but B = a> 1 and False or True returns True, and the actual intention should return False.
If B = False if a> 1 else is True, False is returned correctly. Therefore, it is a substitute for authentic ternary characters.
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
You can use enumerate to retrieve the index and value at a time to avoid using the index. In addition, the second parameter of enumerate can be used to adjust the start position of the index. the default value is 0.
Create a key-value pair using zip
P:
keys = ['Name', 'Sex', 'Age']values = ['Tim', 'Male', 23] dic = dict(zip(keys, values))#{'Age': 23, 'Name': 'Tim', 'Sex': 'Male'}
NP:
dic = {}for i,e in enumerate(keys): dic[e] = values[i]#{'Age': 23, 'Name': 'Tim', 'Sex': 'Male'}
The zip method returns a key-value pair, which is simple and clear.