Home Backend Development Python Tutorial How to make your Python code more pythonic?

How to make your Python code more pythonic?

Oct 17, 2016 pm 05:22 PM

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
Copy after login

NP:

a = 3
b = 1
b >= 1 and b <= a and a < 10 #True
Copy after login

P is a grammar that elementary school students can understand, simple and direct Provincial code ~


Truth Test

P:

name = &#39;Tim&#39;
langs = [&#39;AS3&#39;, &#39;Lua&#39;, &#39;C&#39;]
info = {&#39;name&#39;: &#39;Tim&#39;, &#39;sex&#39;: &#39;Male&#39;, &#39;age&#39;:23 }    
  
if name and langs and info:
    print(&#39;All True!&#39;)  #All True!
Copy after login

NP:

if name != &#39;&#39; and len(langs) > 0 and info != {}:
    print(&#39;All True!&#39;) #All True!
Copy after login

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!

Connection of string lists

P:

def reverse_str( s ):
    return s[::-1]
Copy after login

NP:

def reverse_str( s ):
    t = &#39;&#39;
    for x in xrange(len(s)-1,-1,-1):
        t += s[x]
    return t
Copy after login

string.join() is often used to connect strings in the list, compared to NP, P The method is very efficient and error-free.


List sum, maximum, minimum, product

P:

strList = ["Python", "is", "good"]  
  
res =  &#39; &#39;.join(strList) #Python is good
Copy after login

NP:

res = &#39;&#39;
for s in strList:
    res += s + &#39; &#39;
#Python is good
#最后还有个多余空格
Copy after login

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以防空列表报错
Copy after login

NP:

sum = 0
maxNum = -float(&#39;inf&#39;)
minNum = float(&#39;inf&#39;)
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
Copy after login

You see, using the list comprehension of P, building a new list becomes so simple and intuitive!

The default value of the dictionary

P:

l = [x*x for x in range(10) if x % 3 == 0]
#l = [0, 9, 36, 81]
Copy after login

NP:

l = []
for x in range(10):
    if x % 3 == 0:
        l.append(x*x)
#l = [0, 9, 36, 81]
Copy after login

The get(key,default) method of

dict is used to get the value of key in the dictionary, if it does not exist For this key, the key is assigned the default value default.

Compared with NP, P has less if...else..., which is really the first choice for people who hate if...else...!


for...else... statement

P:

dic = {&#39;name&#39;:&#39;Tim&#39;, &#39;age&#39;:23}  
  
dic[&#39;workage&#39;] = dic.get(&#39;workage&#39;,0) + 1
#dic = {&#39;age&#39;: 23, &#39;workage&#39;: 1, &#39;name&#39;: &#39;Tim&#39;}
Copy after login

NP:

if &#39;workage&#39; in dic:
    dic[&#39;workage&#39;] += 1
else:
    dic[&#39;workage&#39;] = 1
#dic = {&#39;age&#39;: 23, &#39;workage&#39;: 1, &#39;name&#39;: &#39;Tim&#39;}
Copy after login

The else part of

for...else... is used to handle the else part that is not interrupted from the for loop Condition. With it, we don't need to set state variables to check whether the for loop breaks out, which is simple and convenient.

Replacement of ternary symbols

P:

for x in xrange(1,5):
    if x == 5:
        print &#39;find 5&#39;
        break
else:
    print &#39;can not find 5!&#39;
#can not find 5!
Copy after login

NP:

find = False
for x in xrange(1,5):
    if x == 5:
        find = True
        print &#39;find 5&#39;
        break
if not find:
    print &#39;can not find 5!&#39;
#can not find 5!
Copy after login

If you have programming experience in C, you will look for alternatives to A ? B : C . You may find that A and B or C look fine, but b = a > 1 and False or True returns True, when the actual intention should be to return False.

Using b = False if a > 1 else True will return False correctly, so it is an authentic ternary symbol replacement.


Enumerate

P:

a = 3  
  
b = 2 if a > 2 else 1
#b = 2
Copy after login

NP:

if a > 2:
    b = 2
else:
    b = 1
#b = 2
Copy after login

Using enumerate can take out the index and value at one time, avoiding using the index to get the value, and the second parameter of enumerate can Adjust the starting position of the index subscript, the default is 0.

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
Copy after login

NP:

for i in xrange(len(array)):
    print i, array[i]
#0 1
#1 2
#2 3
#3 4
#4 5
Copy after login
The zip method returns a tuple, use it to create key-value pairs, simple and clear .

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles