Python is a simple and flexible programming language, and there are many ways to implement a small function. For example, in my previous article “From Easy to King, Save 90% memory,” I described how k-V data structures can be implemented in many different ways.
However, different implementations can be quite different.
There is a huge difference between an ordinary implementation and a good one in terms of memory footprint and execution efficiency.
In this article, I will introduce you to 8 Python programming tips to help you write more elegant Python code.
1. enumerate()
alternativerange(len())
** Problem: ** iterates through a list and sets values less than 0 to 0.
Traversing a list is a common operation in the development process.
Most Python developers are used to using the range(len()) syntax, which is introduced in many tutorials and books, and is therefore the default way for many students to iterate over lists.
Using the enumerate() function is a better choice for traversing lists because it can fetch both the index and the current item, which is useful in many scenarios. Using range(len()) doesn’t work with both the index and the current item.
Here’s a comparison of the two ways:
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
Copy the code
2. List expression substitutionfor
cycle
** Problem: ** find the square of ownership in a list.
The more common for loop looks like this:
squares = []
for i in range(10):
squares.append(i*i)
Copy the code
With a list expression, it looks like this:
squares = [i*i for i in range(10)]
Copy the code
One line of code can do what three lines of code would do in the for loop.
List expressions are very powerful and can also be used in conjunction with conditional statements.
However, don’t overuse list expressions. Because it makes code simpler and increases the cost of reading comprehension. Therefore, it is not recommended to use list expressions in complex statements.
Use 3.set
duplicate removal
** Problem: ** Deduplicates elements in a list.
When seeing this problem, some students will think of many complicated methods, traversal, dictionary….
List elements can be de-duplicated with a single line of code called set.
Because a set is an unordered collection, it automatically removes duplicate elements from the list.
,2,3,4,5,6,7,7,7 my_list = [1] the set (my_list) # set ([1, 2, 3, 4, 5, 6, 7])Copy the code
4. Use generators to save memory
** Question: ** How can I save memory if there are 10000 elements in the list?
If there are few elements, using lists is a good choice. If there are too many elements, the list becomes very memory intensive.
The visual explanation generator, as its name suggests, generates one element at a time, and as you call it, it increments the next element. It’s a very memory saving function if you don’t call it.
So just to compare that,
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
Copy the code
As you can see, for the same 10,000 elements, the memory footprint of using lists is 684.5 times that of using generators.
5. Use.get()
and.setdefault()
Access to a dictionary
** Problem: ** accesses a value in a dictionary.
When we access the dictionary through key, if the k-v value is not present in the dictionary, it will report an error, terminate the program, and return KeyError.
So it’s better to use the.get() method in the dictionary. 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 default value we specified, or None if we didn’t specify it.
My_dict = {'item': 'football', 'price': 10.00} price = my_dict['count'] # KeyError! # better: price = my_dict.get('count', 0) # optional default valueCopy the code
Counting with a dictionary is a common operation.
In this process, you need to determine whether the key is present in the dictionary and assign it to the default value, whereas.setdefault() can be used to set the default value directly to the dictionary.
6. Usecollections.Counter
count
** Problem: ** Counts the number of occurrences of elements in a list field and filters the elements that occur most frequently.
In the project development, counting, statistical frequency, is often encountered problems.
Python’s standard module, collections.Counter, provides many useful and powerful technical methods that can do a lot of complicated logic with a single line of code.
For example, if you want 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
Copy the code
7. Use支那
Merge field
** Problem: ** gives you two dictionaries to merge elements into the same field
Instead of going through two layers to read the elements in the dictionary and then merging them into the same dictionary, a simple double star ** does the trick.
This syntax is new since Python3.5 and was not available before Python3.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'}
Copy the code
Use 8.if x in list
Reduced conditional statement
** Problem: ** determines whether it is equal to the value of an element in the list.
Students who are accustomed to C/C++, Java and other programming languages for development will choose == or! When they encounter conditional statements. = to judge.
If you have a lot of criteria, you need to write a very long statement, for example,
colors = ["red", "green", "blue"]
c = "red"
if c == "red"or c == "green"or c == "blue":
print("is main color")
Copy the code
In Python, however, conditional statements are greatly simplified and can be solved using in, which is a short line of code.
colors = ["red", "green", "blue"]
c = "red"
if c in colors:
print("is main color")
Copy the code
The eight Python tips described above, while seemingly simple, may seem like child’s play to some Python developers. However, for students who have just come out of books or tutorials, it is inevitable that they will fall into the relatively narrow scope of books.
At this time, you need to see more and learn more. Looking at other people’s code, having them look at your code, and in the process learning little tricks that you didn’t know were valuable to improving your coding skills. And this applies not just to Python, but to any other programming language.
Dry recommended
In order to facilitate everyone, I spent half a month’s time to get over the years to collect all kinds of iso technical finishing together, content including but not limited to, Python, machine learning, deep learning, computer vision, recommendation system, Linux, engineering, Java, content of up to 5 t +, I put all the resources download link to a document, The directory is as follows:
All dry goods to everyone, hope to be able to support it!
https://http://pan.baidu.com/s/1eks7CUyjbWQ3A7O9cmYljA (code: 0000)