Pythonic is very pythonic if translated into Chinese. There are many uses of the noun structure "very +" in China, such as: "very girly", "very national football team", "very CCTV", etc. ·
For the sake of simplicity below, we use P to represent the pythonic writing method, and NP to represent the non-pythonic writing method. Of course, this P-NP is not that P-NP.
Why pursue pythonic?
Compared with NP, P’s writing method is concise, clear, and elegant. Most of the time, the execution efficiency is high, and the less code, the less error-prone it is. I think that good programmers should pursue the correctness, simplicity and readability of the code when writing code. This is exactly the spirit of pythonic.
For programmers (such as myself) who have experience in other programming languages and are new to Python, recognizing the pythonic writing method will bring more convenience and efficiency when writing Python code, and the main readers of this article It will also be this group of programmers.
N examples of P and NP will be given below for readers’ reference.
P vs. NP example
Chained comparison
P:
a = 3 b = 1 1 <= b <= a < 10 #True
NP:
a = 3 b = 1 b >= 1 and b <= a and a < 10 #True
P is a grammar that elementary school students can understand, simple and direct Provincial code ~
Truth 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, the way P is written is to directly judge whether it is true or false for any object without writing judgment conditions. , which can not only ensure correctness, but also reduce the amount of code.
True and false value table (you can save a lot of code if you remember false!)
True False
True False
Any non-empty string Empty string''
Any non-0 number Number 1
P’s writing method is simple, and after testing, it is more efficient.
If used to detect palindromes, it is a sentence of input == input[::-1], how elegant!
def reverse_str( s ): return s[::-1]
def reverse_str( s ): t = '' for x in xrange(len(s)-1,-1,-1): t += s[x] return t
strList = ["Python", "is", "good"] res = ' '.join(strList) #Python is good
NP:
res = '' for s in strList: res += s + ' ' #Python is good #最后还有个多余空格
After simple testing, in num When the length of List is 10000000 , summing the list on my machine, P takes 0.6s, NP takes 1.3s, nearly twice the difference. So don’t reinvent your own wheel.
List comprehension
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 mul prod = reduce(mul, numList, 1) #prod = 120 默认值传1以防空列表报错
NP:
sum = 0 maxNum = -float('inf') minNum = float('inf') prod = 1 for 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
The default value of the dictionary
l = [x*x for x in range(10) if x % 3 == 0] #l = [0, 9, 36, 81]
l = [] for x in range(10): if x % 3 == 0: l.append(x*x) #l = [0, 9, 36, 81]
dic = {'name':'Tim', 'age':23} dic['workage'] = dic.get('workage',0) + 1 #dic = {'age': 23, 'workage': 1, 'name': 'Tim'}
if 'workage' in dic: dic['workage'] += 1 else: dic['workage'] = 1 #dic = {'age': 23, 'workage': 1, 'name': 'Tim'}
Replacement of ternary symbols
for x in xrange(1,5): if x == 5: print 'find 5' break else: print 'can not find 5!' #can not find 5!
find = False for x in xrange(1,5): if x == 5: find = True print 'find 5' break if not find: print 'can not find 5!' #can not find 5!
a = 3 b = 2 if a > 2 else 1 #b = 2
if a > 2: b = 2 else: b = 1 #b = 2
Use zip to create key-value pairs
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
for i in xrange(len(array)): print i, array[i] #0 1 #1 2 #2 3 #3 4 #4 5