Make your Python code more pythonic (concise, clear, elegant) _lua

Source: Internet
Author: User
Tags mul zip

What is Pythonic?

Pythonic is very python if translated into Chinese. Very much the use of noun structure in China, such as: Very Niang, very national football, CCTV and so on.

My understanding is that very + nouns express a special and emphatic meaning. So python can be understood as: Only Python can do, and different from other languages, in fact, is Python's idiomatic and unique writing.

Replaces the value of two variables.

It's a very Python notation:

Copy Code code as follows:

A,b = B,a

Not Python's writing:

Copy Code code as follows:

temp = a
A = b
b = Temp

The example above completes the interchange of the a,b with the pack and unpack of the tuples, avoids the use of temp for temporary variables, and uses only one line of code.

The following in order to briefly, we use P to express pythonic, NP to express non-pythonic, of course, this P-NP is not P-NP.

Why do you want to pursue pythonic?

Compared to the np,p writing concise, clear, elegant, most of the time the implementation of high efficiency, the less code is more error-prone. I think a good programmer in writing code, should pursue the correctness of the code, simplicity and readability, this is precisely the spirit of pythonic.

For programmers with other programming language experiences, such as myself, when writing Python code, recognizing that Pythonic is more convenient and efficient, the main reader of this article will be the programmers.

The following n examples of P and NP are given for readers and their own reference.

At the end of this article, we will list references, which seem to me to be of great value.

Example of P vs. np

Chain comparison

P:

Copy Code code as follows:

A = 3
b = 1

1 <= b <= a < #True

Np:

Copy Code code as follows:

b >= 1 and B <= A and a < #True

P is the primary school students can understand the grammar, simple direct province code ~

Truth test

P:

Copy Code code as follows:

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:

Copy Code code as follows:

If name!= ' and Len (langs) > 0 and Info!= {}:
Print (' All true! ') #All true!

In short, P's writing is for any object, directly to determine the true and false, no need to write judgment conditions, so as to ensure correctness, but also reduce the amount of code.

True and False Value table (remember the fake you can save a lot of code!) )

really Fake
True False
Any non-empty string Empty string '
Any non 0 digits Number 0
Any non-empty container Empty container [] () {} set ()
Any other not false None

String inversion

P:

Copy Code code as follows:

def reverse_str (s):
return S[::-1]

Np:

Copy Code code as follows:

def reverse_str (s):
t = '
For x in Xrange (Len (s) -1,-1,-1):
T + + s[x]
Return T

P is a simple way of writing, and has been tested and more efficient.

If used to detect palindrome, is a word input = = Input[::-1], how elegant!

Connection to a list of strings

P:

Copy Code code as follows:

Strlist = ["Python", "is", "good"]

res = '. Join (strlist) #Python is good

Np:

Copy Code code as follows:

res = '
For S in Strlist:
Res + S + '
#Python is good
#最后还有个多余空格

String.Join () is often used to connect strings in a list, which is highly efficient and does not make mistakes relative to np,p.

List summation, max, Min, product

P:

Copy Code code as follows:

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) #prod = 120

Np:

Copy Code code as follows:

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 = Maxnum = 5 Minnum = 1 PROD = 120

After a simple test, when the length of the numlist is 10000000, the list is summed on my machine, p is time-consuming 0.6s,np 1.3s, and nearly twice times the gap. So don't build the wheels yourself.

List inference Type

P:

Copy Code code as follows:

L = [x*x for x in range (ten) if x% 3 = 0]
#l = [0, 9, 36, 81]

Np:

Copy Code code as follows:

L = []
For x in range (10):
If x 3 = 0:
L.append (x*x)
#l = [0, 9, 36, 81]

You see, using the list derivation of p, how simple and intuitive it becomes to build a new list!

Default values for Dictionaries

P:

Copy Code code as follows:

DIC = {' name ': ' Tim ', ' age ': 23}

dic[' workage '] = dic.get (' Workage ', 0) + 1
#dic = {' age ': Workage ': 1, ' name ': ' Tim '}

Np:

Copy Code code as follows:

If ' Workage ' in dic:
dic[' workage '] + + 1
Else
dic[' workage '] = 1
#dic = {' age ': Workage ': 1, ' name ': ' Tim '}

The Dict Get (Key,default) method is used to obtain the value of the key in the dictionary, and if the key does not exist, the key is assigned default value.
P compared to NP-less if...else ..., actually hate if...else ... The choice of people!

For...else ... Statement

P:

Copy Code code as follows:

For x in Xrange (1,5):
If x = 5:
print ' Find 5 '
Break
Else
print ' Can not find 5! '
#can not find 5!

Np:

Copy Code code as follows:

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!

For...else ... The else part of the is used to handle situations that are not interrupted from the for loop. With it, we do not have to set the state variable to check whether the for loop has a break out, simple and convenient.

Substitution of ternary characters

P:

Copy Code code as follows:

A = 3

b = 2 If a > 2 else 1
#b = 2

Np:

Copy Code code as follows:

If a > 2:
b = 2
Else
b = 1
#b = 2

If you have C programming experience, you will be looking for a? A substitute for b:c. You may find A and B or C to 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 the authentic ternary substitution.

Enumerate

P:

Copy Code code as follows:

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:

Copy Code code as follows:

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 adjusts the starting position of the index subscript, which defaults to 0.

Create a key value pair using zip

P:

Copy Code code as follows:

Keys = [' Name ', ' Sex ', ' age ']
values = [' Tim ', ' Male ', 23]

DIC = Dict (Zip (keys, values))
#{' age ': ' Name ': ' Tim ', ' Sex ': ' Male '}

Np:

Copy Code code as follows:

DIC = {}
For i,e in Enumerate (keys):
Dic[e] = Values[i]
#{' age ': ' Name ': ' Tim ', ' Sex ': ' Male '}

The Zip method returns a tuple and uses it to create a key-value pair, which is straightforward.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.