How to write Pythonic code

Because of the simplicity of the language, Python allows us to write code in a human way of thinking. It is easier for novices to learn, and veterans love it even more.

To write Pythonic (elegant, authentic, and tidy) code, you also need to observe the big cow codes. Here, Ming Ge has collected some common Pythonic writing methods to help you develop the habit of writing excellent code.

01. Variable exchange

Exchanging the values of two variables, you normally want to use an intermediate temporary variable to transition.

tmp = a
a = b
b = tmp

Can be solved with one line of code (and does not affect readability), never need three lines of code.

a,b = b,a

02. List comprehension

Below is a very simple for loop.

my_list =[]for i inrange(10):
 my_list.append(i*2)

In a for loop, if the logic is relatively simple, it is better to try the list comprehension of the list. Although there is only one line of code, the logic is clear.

my_list =[i*2for i inrange(10)]

03. Single line expression

In the above two cases, multiple lines of code were written into one line of code in another way.

This does not mean that the fewer lines of code, the more Pythonic.

For example, writing like this is not recommended.

print('hello');print('world')if x ==1:print('hello,world')if<complex comparison> and <other complex comparison>:
 # do something

The suggestion is to follow the following wording

print('hello')
print('world')

if x ==1:print('hello,world')

cond1 =<complex comparison>
cond2 =<other complex comparison>if cond1 and cond2:
 # do something

04. Traversal with index

When using a for loop, how to get the corresponding index, beginners are used to using the range + len function

for i inrange(len(my_list)):print(i,"-->", my_list[i])

A better approach is to use the built-in function enumerate

for i,item inenumerate(my_list):print(i,"-->",item)

05. Sequence unpacking

Use * to unpack a list

a,*rest =[1,2,3]
# a =1, rest =[2,3]

a,*middle, c =[1,2,3,4]
# a =1, middle =[2,3], c =4

06. String splicing

If all the elements in a list (or iterable object) are string objects and want to connect them, the usual approach is

letters =['s','p','a','m']
s=""forletin letters:
 s +=let

The more recommended approach is to use the join function

letters =['s','p','a','m']
word =''.join(letters)

07. True and false judgment

To judge whether a variable is true (false), novices are used to directly use == to compare with True, False, None

if attr == True:print('True!')if attr == None:print('attr is None!')

In fact, containers without any elements such as &quot;&quot;, [], and {} are all false values. You can directly use if not xx to judge.

if attr:print('attr is truthy!')if not attr:print('attr is falsey!')

08. Access dictionary elements

When directly using [] to access the elements in the dictionary, if the key does not exist, an exception will be thrown, so the new club may first determine whether there is this key, and then take it.

d ={'hello':'world'}if d.has_key('hello'):print(d['hello'])    # prints 'world'else:print('default_value')

The more recommended way is to use get to get it, if there is no such key, it will return None by default (of course you can also set the default return value)

d ={'hello':'world'}print(d.get('hello','default_value')) # prints 'world'print(d.get('thingy','default_value')) # prints 'default_value'

09. Operation list

The following code will filter the elements in the list according to conditions

a =[3,4,5]
b =[]for i in a:if i >4:
  b.append(i)

In fact, you can use list comprehension or higher-order function filter to achieve

a =[3,4,5]
b =[i for i in a if i >4]
# Or:
b =filter(lambda x: x >4, a)

In addition to filter, two functions of map and reduce are also very useful

a =[3,4,5]
b =map(lambda i: i +3, a)
# b:[6,7,8]

10. File reading

File reading is a very common operation, after using the handle, you need to manually call the close function to close the handle

fp =open('file.txt')print(fp.read())
fp.close()

If the code is too long, even if you know you need to manually close the handle, you will often miss it. Therefore, it is recommended to develop a habit of using with open to read and write files, the context manager will automatically perform the operation of closing the handle

withopen('file.txt')as fp:for line in fp.readlines():print(line)

11. Code continuation

Putting a long string in one line greatly affects the readability of the code (the code below can slide to the left)

long_string ='For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say “I’m going to sleep.”'

People who pay attention to code readability will use three quotation marks \ to continue writing

long_string ='For a long time I used to go to bed early. ' \
    ' Sometimes, when I had put out my candle, ' \
    ' my eyes would close so quickly that I had not even time to say “I’m going to sleep.”'

However, for me, I prefer to use parentheses to wrap ()

long_string =("For a long time I used to go to bed early. Sometimes, ""when I had put out my candle, my eyes would close so quickly ""that I had not even time to say “I’m going to sleep.”")

The same is true when guiding the package

from some.deep.module.inside.a.module import(
 a_nice_function, another_nice_function, yet_another_nice_function)

12. Explicit code

Sometimes out of necessity, we will use some special magic to adapt the code to more uncertain scenes.

def make_complex(*args):
 x, y = args
 returndict(**locals())

But if not necessary, please don't do that. Unreasonably increasing the uncertainty of the code will make the original dynamic language write more dynamic code.

def make_complex(x, y):return{'x': x,'y': y}

13. Use placeholders

For variables that are not needed but have to be received, please use placeholders

filename ='foobar.txt'
basename, _, ext = filename.rpartition('.')

14. Chained comparison

For the following writing

score =85if score >80 and score <90:print("good")

There is actually a better way to write

score =85if80< score <90:print("good")

If you understand the chain comparison operation above, then you should know why the output of the following line of code is False

>>> False == False == True 
False

15. Trinocular operation

For simple judgment and assignment

age =20if age >18:
 type ="adult"else:
 type ="teenager"

In fact, you can use the trinocular calculation to do it in one line.

age =20  
b ="adult"if age >18else"teenager"

Recommended Posts

How to write Pythonic code
How to comment python code
python how to view webpage code
How to write python configuration file
How to wrap in python code
How to write classes in python
How to write return in python
How to write win programs in python
How to write try statement in python
How to install Visual Studio Code on Ubuntu 20.04
How to install Visual Studio Code on CentOS 8
How to install openssh from centos 7 source code
How to use code running assistant in python
How to set code auto prompt in python
Teach you how to write games in python
How to write a confession program in python
Python how to move the code collectively right
How to read and write files with Python
How to install Visual Studio Code on Ubuntu 20.04
How to upgrade to Ubuntu 20.04
How to upgrade to Ubuntu 20.04
Python code to find bugs (2)
Python code to find bugs(7)
Python code to find bugs(4)
Python code to find bugs (3)
Python code to find bugs(9)
How to learn python quickly
How to uninstall python plugin
Python code to find bugs(6)
Python code to find bugs (1)
Python code to find bugs(8)
How to understand python objects
Python code to find bugs(5)
How to use python tuples
How to upgrade to Ubuntu 16.04 LTS
How to install Helm in Ubuntu
How to install jdk1.8 on centOS7
How to install MySQL on CentOS 8
How to install Ruby on Ubuntu 20.04
How to install Memcached on Ubuntu 20.04
How to install https certificate (ubuntu+apache2)
How to upgrade CentOS7 to CentOS8 (detailed steps)
How to use Python&#39;s filter function
How to use python&#39;s help function
How to install Java on Ubuntu 20.04
How to install MySQL on Ubuntu 20.04
How to use hanlp in ubuntu
How to install Memcached on CentOS 8
How to install R on CentOS 8
How to install Elasticsearch on Ubuntu 20.04
How to install FFmpeg on CentOS 8
How to install Virtualbox on CentOS 8
How to install Protobuf 3 on Ubuntu
How to install Nginx on Ubuntu 20.04
How to install TensorFlow on CentOS 8
Use C++ to write Python3 extensions
How to install Node.js on Ubuntu 16.04
How to Update to gcc4.9.x on Centos7
How to install MySQL on Ubuntu 20.04
How to install TeamViewer on CentOS 8
How to install Perl 5 on CentOS