Table of Contents
Copying a list using list comprehensions
Multiply the elements in the list
Deleting elements from a list
Use dict() to convert two lists into dictionary key-value pairs
Summary
Home Backend Development Python Tutorial Four Python deductive development techniques to make your code more efficient

Four Python deductive development techniques to make your code more efficient

Apr 22, 2023 am 09:40 AM
python Skill develop

For data science, Python is usually widely used for data processing and transformation. It provides powerful data structure processing functions to make data processing more flexible. What does "flexibility" mean here?

This means that there are always multiple ways to achieve the same result in Python, we always have different methods and need to choose the one that is easy to use, saves time and gives better control.

It is impossible to master all these methods. So here is a list of 4 Python tips you should know when working with any type of data.

Four Python deductive development techniques to make your code more efficient

List comprehension List comprehension is an elegant and most Python-friendly way to create lists. Compared to for loops and if statements, list comprehensions have a much shorter syntax for creating a new list based on the values ​​of an existing list. So let's see how this feature gets a copy of the list.

Copying a list using list comprehensions

Sometimes you need to create a copy of an existing list. The simplest answer is .copy(), which allows you to copy the contents of one list to another (new) list.

For example, a list of integers original_list.

original_list = [10,11,20,22,30,34]
Copy after login

This list can be copied simply using the .copy() method.

duplicated_list = original_list.copy()
Copy after login

List comprehensions can get exactly the same output. Copying a list is a great example of understanding list comprehensions.

Look at the code below.

duplicated_list = [item for item in original_list]
Copy after login

This is not to say that it is better to use list comprehensions when copying lists, but it is to say that this case is the best for introducing the working method of list comprehensions.

Next, let’s see how list comprehensions make life easy when performing mathematical operations on each element of a list.

Multiply the elements in the list

The simplest or direct method of multiplication is to use the multiplication operator, which is *

For example, if you want to use a scalar (i.e. the number 5) Multiply each item in the list. You definitely can't use original_list*5 here because it will create 5 copies of the list.

In this scenario, the best answer is a list comprehension, as shown below.

original_list = [10,11,20,22,30,34]
 multiplied_list = [item*5 for item in original_list]
 
 # Output
 [50, 55, 100, 110, 150, 170]
Copy after login

The operation here is not limited to multiplying a number. Complex operations can be performed on each element of the original list.

For example, suppose you want to calculate the cube of the square root of each term. You can solve it in one line.

multiplied_list = [math.sqrt(item)**3 for item in original_list]
 
 # Output
 [31.6227766016838,
36.4828726939094,
89.4427190999916,
103.18914671611546,
164.31676725154983,
198.25236442474025]
Copy after login

The function sqrt used to calculate the square root of a number belongs to the library math, so you need to import it before using it in this example.

Similar to the built-in functions shown above, it is also possible to use user-defined functions on each element of the list.

For example, the simple function shown below.

def simple_function(item):
item1 = item*10
item2 = item*11
return math.sqrt(item1**2 + item2**2)
Copy after login

This user-defined function can be applied to each item in the list.

multiplied_list = [simple_function(item) for item in original_list]
 
 # Output
 [148.66068747318505,
163.52675622050356,
297.3213749463701,
327.0535124410071,
445.9820624195552,
505.4463374088292]
Copy after login

List comprehensions are even more useful in practical scenarios. Usually in analysis tasks you need to remove certain types of elements from a list, such as eliminating nan elements. List comprehensions are the perfect tool for these tasks.

Deleting elements from a list

Filtering data based on specific criteria is one of the common tasks of selecting a desired data set, and the same logic is also used in list comprehensions.

Suppose you have the list of numbers mentioned below.

original_list = [10, 22, -43, 0, 34, -11, -12, -0.1, 1]
Copy after login

You want to keep only positive values ​​from this list. So logically you want to keep only those items that evaluate to TRUE for conditional items > 0.

new_list = [item for item in original_list if item > 0]
 
 # Output
 [10, 22, 34, 1]
Copy after login

The if clause is used to delete negative values. You can apply any condition using if clause to remove any item from the list.

For example, when you want to delete all items whose square is less than 200, all you need to do is to mention the conditional item **2 > 200 in the list synthesis, as shown below.

new_list = [item for item in original_list if item**2 > 200]
 
 # Output
 [22, -43, 34]
Copy after login

When dealing with real data sets, the conditions for filtering list items may be much more complex, this method is fast and easy to understand.

Use dict() to convert two lists into dictionary key-value pairs

Sometimes you need to create a dictionary from the values ​​in two lists. Instead of typing them in one by one, you can use dictionary comprehensions (dictionary comprehension), which is an elegant and concise way to create a dictionary!

It works exactly like a list comprehension, the only difference is - when creating a list comprehension, you wrap everything in square brackets, such as [], whereas in a dictionary comprehension, you wrap everything Enclosed in curly braces, such as {}.

Suppose there are two lists - fields and details - as shown below.

fields = [‘name’, ‘country’, ‘age’, ‘gender’]
 details = [‘pablo’, ‘Mexico’, 30, ‘Male’]
Copy after login

A simple way is to use a dictionary comprehension like this -

new_dict = {key: value for key, value in zip(fields, details)}
 
 # Output
 {'name': 'pablo', 'country': 'Mexico', 'age': 30, 'gender': 'Male'}
Copy after login

The important thing to understand here is how the function zip works.

In Python, the zip function accepts iterable objects such as strings, lists, or dictionaries as input and returns them aggregated into tuples.

So, in this case zip has formed a pair of each item from the list fields and details. When using key:value in a dictionary comprehension, simply unpack this tuple into individual key-value pairs.

This process even gets faster when using the built-in dict() constructor in Python (for creating dictionaries), since dict() is at least 1.3 times faster than dictionary comprehensions!

So we need to use this constructor with the zip() function, its syntax is much simpler - dict(zip(fields, details))

Summary

As As I mentioned at the beginning, Python is very flexible as there are multiple ways to achieve the same result. Depending on the complexity of the task you need to choose the best way to achieve it.

I hope this article can be useful to you. If there is any other way to do the same thing I mentioned in this article, please let me know.

The above is the detailed content of Four Python deductive development techniques to make your code more efficient. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How does PS feathering control the softness of the transition? How does PS feathering control the softness of the transition? Apr 06, 2025 pm 07:33 PM

The key to feather control is to understand its gradual nature. PS itself does not provide the option to directly control the gradient curve, but you can flexibly adjust the radius and gradient softness by multiple feathering, matching masks, and fine selections to achieve a natural transition effect.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

How to set up PS feathering? How to set up PS feathering? Apr 06, 2025 pm 07:36 PM

PS feathering is an image edge blur effect, which is achieved by weighted average of pixels in the edge area. Setting the feather radius can control the degree of blur, and the larger the value, the more blurred it is. Flexible adjustment of the radius can optimize the effect according to images and needs. For example, using a smaller radius to maintain details when processing character photos, and using a larger radius to create a hazy feeling when processing art works. However, it should be noted that too large the radius can easily lose edge details, and too small the effect will not be obvious. The feathering effect is affected by the image resolution and needs to be adjusted according to image understanding and effect grasp.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

See all articles