"Python" 8 tips to improve the quality of Python code

Posted by dennyx on Mon, 07 Mar 2022 03:11:35 +0100

enumerate() instead of range(len())

Problem: traverse a list and set the value less than 0 to 0.

Traversing the list is an operation often involved in the development process.

Most Python developers are used to using range(len()) syntax, which is introduced in many tutorials and books. Therefore, many students choose to use this method to traverse the list by default.

In the traversal list, it is a better choice to use the enumerate() enumeration function, because it can get the index and the current item at the same time, which is very practical in many scenarios. However, using range(len()) can't give consideration to both index and current item.

data = [1, 2, -3, -4]

# range(len())
for i in range(len(data)):
    if data[i] < 0:
        data[i] = 0


# enumerate()
data = [1, 2, -3, -4]
for idx, num in enumerate(data):
    if num < 0:
        data[idx] = 0

List expression instead of for loop

Question: find the square of ownership in a list.

If you use the more common for loop method, it is as follows:

squares = []
for i in range(10):
    squares.append(i*i)

The list expression is as follows:

squares = [i*i for i in range(10)]
One line of code can be implemented The function of the for loop can only be realized by 3 lines of code.

List expressions are very powerful and can also be used in conjunction with conditional statements.

However, do not overuse list expressions. Because it not only makes the code simple, but also increases the cost of reading and understanding. Therefore, it is not recommended to use list expressions in some complex statements.

Use set to remove duplicate

Problem: de duplication of elements in a list.

When seeing this problem, some students will think of many complex methods, such as traversal, Dictionary

If you use a line of set code, you can achieve the de duplication of list elements.

Because set is an unordered set, it will automatically remove duplicate elements from the list.

my_list = [1,2,3,4,5,6,7,7,7]
set(my_list)
# set([1, 2, 3, 4, 5, 6, 7])

Save memory with generator

Question: if there are 10000 elements in the list, how to save memory?

If there are fewer elements, using lists is a good choice. If there are a certain number of elements, the list becomes very memory consuming.

The image interpretation generator, just like its name, generates only one element at a time. When it is called, it will gradually generate the next element. If you do not call it, it is a very memory saving function.

Let's compare,

import sys

my_list = [i for i in range(10000)]
print(sys.getsizeof(my_list), 'bytes') # 87616 bytes

my_gen = (i for i in range(10000))
print(sys.getsizeof(my_gen), 'bytes') # 128 bytes
It can be seen that the same is 10000 elements. In terms of memory consumption, the use of list is 684.5 times that of generator.

use. get() and setdefault() ACCESS Dictionary

Problem: access a value in a dictionary.

When accessing the dictionary through the key, if there is no K-V value in the dictionary, it will report an error, terminate the program, and return KeyError.

So a better way is to use it in a dictionary get() method. This also returns the value of the key, but it does not raise a key error if the key is not available. Instead, it returns the specified default value or None if it is not specified.

my_dict = {'item': 'football', 'price': 10.00}
price = my_dict['count'] # KeyError!

# better:
price = my_dict.get('count', 0) # optional default value

Counting with a dictionary is a common operation.

In this process, you need to first judge whether there is a key in the dictionary, and then assign it to the default value setdefault() can directly set default values for the dictionary.

Use collections Counter count

Problem: count the occurrence times of elements in the list field and filter the elements with the highest frequency.

In the project development, counting and counting frequency are often encountered problems.

Python comes with the standard module collections Counter provides many easy-to-use and powerful technical methods. It only needs one line of code to complete a lot of work that can be completed by complex logic.

For example, to count the most frequent elements in a list, you can do this:

from collections import Counter

my_list = [10, 10, 10, 5, 5, 2, 9, 9, 9, 9, 9, 9]
counter = Counter(my_list)

most_common = counter.most_common(2)
print(most_common) # [(9, 6), (10, 3)]
print(most_common[0]) # (9, 6)
print(most_common[0][0]) # 9

Use * * to merge fields

Question: two dictionaries, merge elements into the same field

You don't need to go through two layers of traversal to read the elements in the dictionary, and then merge these elements into the same dictionary. You only need a simple double asterisk * * to realize this requirement.

This syntax is a new syntax since Python 3.5, which is in Python 3.5 Cannot be used before 5.

Here's an example:

d1 = {'name': 'Alex', 'age': 25}
d2 = {'name': 'Alex', 'city': 'New York'}
merged_dict = {**d1, **d2}
print(merged_dict)
# {'name': 'Alex', 'age': 25, 'city': 'New York'}

Simplify conditional statements with if x in list

Question: determine whether it is equal to the value of an element in the list.

Students who are used to developing with C/C + +, Java and other programming languages will choose = = or when they encounter conditional statements= To judge.

If there are many conditions to judge, you need to write a long statement, such as:

colors = ["red", "green", "blue"]

c = "red"

if c == "red"or c == "green"or c == "blue":
    print("is main color")

In Python, conditional statements are greatly simplified. You can use in to solve this problem, which can be completed in a short line of code.

colors = ["red", "green", "blue"]

c = "red"

if c in colors:
    print("is main color")

Finally, I wish you progress every day!! The most important thing to learn Python is mentality. We are bound to encounter many problems in the process of learning. We may not be able to solve them if we want to break our head. This is normal. Don't rush to deny yourself and doubt yourself. If you have difficulties in learning at the beginning and want to find a python learning and communication environment, you can join us, receive learning materials and discuss together

 

 

Topics: Python Back-end