Posted by kante on Sat, 27 Jun 2020 10:19:09 +0200

Yunqi information:[ Click to see more industry information]
Here you can find the first-hand cloud information of different industries. What are you waiting for? Come on!

Python is very friendly to beginners. Many people choose Python when they start to learn programming. Easy to use is the first advantage you find when you touch it. After learning more, you may be attracted by its flexibility - you can do the same function in various ways.

In fact, there are more convenient solutions. The more concise the code, the higher the readability and long-term existence. There are many ways to write simple code in Python. In this article, I want to share with you five tips that I find particularly useful in daily Python projects.

### 1. List, dictionary and set derivation

List derivation is one of the favorite features of many Python programmers. This is a neat way to create lists from iterators. The basic syntax is [expression for x in iterable]. You can see some examples to learn more about its usage:

``````>>># Create a list for subsequentoperations
>>> numbers = [1, 2, 3, 4, 5, 6]
>>>
>>># Typical way to create a list consisting of squares
>>> squares0 = []
>>>for number in numbers:
...     squares0.append(number*number)
...
>>># List comprehensions
>>> squares1 = [number*number for number in numbers]``````

Without using list derivation, you have to create an empty list and add the square of each number by running the for loop, which usually takes three lines of code. With column derivation, you can build the same square list in just one line of code.

Besides list derivation, there are dictionary and set derivation. Dictionary derivation has the basic syntax {key_expr:value_expr for x in iterable}, the basic syntax of set derivation is {expression for X in Iterable}. Similar to the list derivation example, multiple lines of code are required to build the required dictionaries and collections without using the derivation.

``````>>># Dictionary comprehension
>>> squares_dict = {number: number*number for number in numbers}
>>> squares_dict
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
>>>
>>># Set comprehension
>>> numbers_dups = [1, 2, 3, 4, 3, 2, 1]
>>> squares_set = {number*number for number in numbers_dups}
>>> squares_set
{16, 1, 4, 9}``````

### 2.Lambda function

Lambda functions are anonymous functions in Python and are usually used for small-scale operations. Lambda function can take one or more parameters, only one expression, and its syntax is lambda p arameters:expression .

I'll use the built-in sorted () function to demonstrate the use of lambda functions. Specifically, the sorted() function uses the key function to sort the iterations, which is specified by the key parameter. Instead of declaring regular functions with the def keyword, we can use lambda functions as key parameters.

``````>>># Create a list of students with theirgrading information
>>> grades = [{ name :  John ,  grade : 95}, { name :  Aaron ,  grade : 92}, { name :  Jennifer ,  grade : 100}]
>>>
>>># Sort using a regular function
...
[{ name :  Aaron ,  grade : 92}, { name :  John ,  grade : 95}, { name :  Jennifer ,  grade : 100}]
>>>
>>># Sort using a lambda
[{ name :  Aaron ,  grade : 92}, { name :  John ,  grade : 95}, { name :  Jennifer ,  grade : 100}]``````

As shown above, you can use the lambda function to write more concise commands that call the sorted () function. Before you can use regular expressions, you must declare the function before you can use the sorted() function, which must be more cumbersome than using the lambda function directly.

### 3. Named tuples as data structure

Tuples can store some related data, but it is not easy to use, especially when it comes to specific elements, you must remember the order and use the correct index of specific elements. If you don't want to use tuples, although you can build a custom class to manage related data, the named tuple data type is a very useful lightweight data structure.

Through the collection module, the namedtuple data type adopts the following basic syntax: namedtuple(Typename,field_names). Grammar is not straightforward, but conceptually easy to understand.

Take a look at the example. The ideal feature is to create a data structure that can store student information, including name, gender, and student ID number.

``````>>># Use a custom class
>>>classStudent0:
...     def__init__(self, name, gender, student_id):
...         self.name = name
...         self.gender = gender
...         self.student_id = student_id
...
>>> s0 =Student0( John ,  M , 2020001)
>>>f"Name: {s0.name}; Gender: {s0.gender}; ID #: {s0.student_id}"
Name: John; Gender: M; ID #: 2020001
>>>
>>># Use the namedtuple
>>>from collections import namedtuple
>>>Student1=namedtuple("Student1", ["name", "gender", "student_id"])
>>> s1 =Student1( Jennifer ,  F , 2020002)
>>>f"Name: {s1.name}; Gender: {s1.gender}; ID #: {s1.student_id}"
Name: Jennifer; Gender: F; ID #:2020002 ``````

With the namedtuple module, you can write lightweight data structures in simpler code. Of course, note that custom classes provide more actionable functionality. But if you just want to create a data structure for storing and retrieving data, you can consider using the namedtuple module.

### 4. Use enumerate() and zip() to iterate

One of the key principles of coding is simplification. When processing a series of data, such as a list of numbers, you usually need to do the same for each number in the list. To avoid repeating the same code, you can use the for loop to run iterations of the entire list.

When iterating over a list or any sequence, it is sometimes necessary to know the position of the item in the sequence. There are several ways to do this.

``````>>># Create a list of students based ontheir arrival sequence
>>> students = [ John ,  Aaron ,  Jennifer ,  Ashley ]
>>>
>>># Lengthy way
>>>for index inrange(len(students)):
...     student = students[index]
...     print(f"Arrival # {index+1}: {student}")
...
Arrival# 1: John
Arrival# 2: Aaron
Arrival# 3: Jennifer
Arrival# 4: Ashley
>>>
>>># Concise way
>>>for index, student inenumerate(students, 1):
...     print(f"Arrival # {index}: {student}")
...
Arrival# 1: John
Arrival# 2: Aaron
Arrival# 3: Jennifer
Arrival# 4: Ashley``````

By using the built-in function, enumerate(), you can easily access indexes and elements in a sequence, which is simpler than the first iteration. More importantly, it can set the number to start counting. Set to 1 in the above example.

In addition to the enumerate() function, the zip() function is also useful in iterations. This function creates tuples from multiple iterations without having to specifically create composite iterations for those iterations.

``````>>># Create two lists for zip(), with oneto one match
>>> names = [ John ,  Danny ,  Jennifer ]
>>> scores = [95, 99, 100]
>>>
>>># Lengthy way
>>>for index inrange(len(names)):
...     name, score = names[index], scores[index]
...     print(f"Name: {name}; Score: {score}")
...
Name: John; Score: 95
Name: Danny; Score: 99
Name: Jennifer; Score: 100
>>>
>>># Concise way
>>>for name, score inzip(names, scores):
...     print(f"Name: {name}; Score: {score}")
...
Name: John; Score: 95
Name: Danny; Score: 99
Name: Jennifer; Score: 100``````

Basically, what the zip() function does is take each element from the iteration to form an ordered tuple in each iteration. This makes the code simpler and more readable.

### 5.f string format

Strings are so basic that we use them almost everywhere. A basic application of strings is to use them with certain formats. There are several ways to format a string. What I want to introduce is the f string, which is very simple.

An F string is a string text inserted using the letter F (or F) as a prefix to the string text. To write concise code, the following two use cases prefer the f string:

·Display variables. The most basic use is to display the values of some variables for debugging during development. If you use the traditional format () method, the code will be too long.

``````>>># Construct a list for formatting/debugging
>>> prime_numbers = [2, 3, 5, 7, 11]
>>>
>>># Show the list using format
>>>print("Prime Numbers: {}".format(prime_numbers))
PrimeNumbers: [2, 3, 5, 7, 11]
>>>
>>># Show the list using f-string
>>>print(f"Prime Numbers: {prime_numbers}")
PrimeNumbers: [2, 3, 5, 7, 11]``````

·Add variable / connection string. Instead of using the join () method of + and string, the f string is used very directly for string joins, and they have the highest readability. In practice, it can be used to construct the file path as follows:

``````>>># The folder and extension
>>> folder = ./usr/images
>>> ext = .jpg
>>>
>>># File name is computed from this list
>>> names = [10, 11, 12]
>>>
>>># Construct File paths
>>># Use + for concatenation
>>> paths0 = [folder + / +str(x) + ext for x in names]
>>>
>>># Use join()
>>> paths1 = [  .join([folder,  / , str(x), ext]) for x in names]
>>>
>>># Use f strings
>>> paths2 = [f"{folder}/{x}{ext}"for x in names]``````

The shorter the code is written, the more readable and maintainable the code will be. This is the eternal truth. But keep in mind that concise code should not lead to any potential ambiguity or confusion.

You have to balance simplicity with readability. In case of conflict, consider readability first, even if it requires more code.

[yunqi online class] product technology experts share every day!