Home Backend Development Python Tutorial Things to note when using Python list comprehensions

Things to note when using Python list comprehensions

Dec 01, 2020 pm 05:32 PM
python list comprehension

python视频教程栏目介绍Python列表推导式的使用。

Things to note when using Python list comprehensions

相关免费学习推荐:python视频教程

Python 列表推导式并不是给初学者用的,因为它非常反直觉,甚至对于有其他编程语言背景的人也是如此。

我们接触到 List 的使用时,学习的内容都是零散的。所以我们缺少一个关于如何在各种各样的场景下使用 List 的知识体系。

本文提供了一些 List 的使用指南,尽可能涵盖各个方面。希望本文可以成为你的一站式实用手册。

使用建议

1.建议使用迭代的方式

使用 List 最基本的方式是以一个可迭代对象为基础,创建一个 List 对象,这个可迭代对象可以是任意可以迭代元素的Python对象。使用方法如下。

[expression for item in iterable]
Copy after login

下面这段代码展示了一个使用列表相关技术创建 List 对象的例子。在这个例子中,我们定义了一个 Integer 列表,并基于这个对象创建了保存每个数字的平方数和立方数的 List 对象。

>>> # 创建一个 Integer 列表
>>> integers = [1, 2, 3, 4, 5, 6]
>>> # 创建平方数和立方数列表
>>> powers = [(x*x, pow(x, 3)) for x in integers]
>>> print(powers)
[(1, 1), (4, 8), (9, 27), (16, 64), (25, 125), (36, 216)]
Copy after login

上面的例子把 List 对象当作迭代器使用。我们应该知道,许多类型的对象也是可迭代的,比如 List、Set、Dictionary 和 String 等等。其他数据类型,像 range、map、filter,以及 pandas 包中的 Series、DataFrame,都是可迭代的。下面的代码演示了某些对象的使用方法。

>>> # 使用 range 对象
>>> integer_range = range(5)
>>> [x*x for x in integer_range]
[0, 1, 4, 9, 16]
>>> # 使用 Series 对象
>>> import pandas as pd
>>> pd_series = pd.Series(range(5))
>>> print(pd_series)
0    0
1    1
2    2
3    3
4    4
dtype: int64
>>> [x*x for x in pd_series]
[0, 1, 4, 9, 16]
Copy after login

2.如果只需用到其中的某些元素,应当使用条件判断语句

假设你需要将符合某种条件的元素归集起来,并创建一个 list。下面展示了相关的语法。

[expression for item in iterable if condition]
Copy after login

if 语句用来实现条件判断。下面的代码展示了这种用法的一个简单示例。

>>> # 同样创建一个 Integer 列表
>>> integers = [1, 2, 3, 4, 5, 6]
>>> # 筛选出偶数,创建一个这些偶数的平方数列表
>>> squares_of_evens = [x*x for x in integers if x % 2 == 0]
>>> print((squares_of_evens))
[4, 16, 36]
Copy after login

3.使用条件判断语句

List 对象中还可以使用 if-else 形式的条件判断,语法如下。

[expression0 if condition else expression1 for item in iterable]
Copy after login

这跟前面的那种用法有些类似,别把这两种用法混淆。在本例中,条件语句本身是一个整体。下面的代码提供了一个例子。

>>> # 创建一个 Integer 列表
>>> integers = [1, 2, 3, 4, 5, 6]
>>> # 遍历 integers 中的元素,如果是偶数,取平方数存入新的列表
>>> # 如果是奇数,取立方数存入新的列表
>>> custom_powers = [x*x if x % 2 == 0 else pow(x, 3) for x in integers]
>>> print(custom_powers)
[1, 4, 27, 16, 125, 36]
Copy after login

4.如果有嵌套结构,可以使用嵌套的循环

有可能可迭代对象中的元素自身也是可迭代的,尽管这种情况不太常见。如果你对嵌套的可迭代对象有兴趣,可以使用 for 来实现循环嵌套。语法如下。

[expression for item_outer in iterable for item_inner in item_outer]
# 与下面的代码等同
for item_outer in iterable:
    for item_inner in item_outer:
        expression
Copy after login

上面的代码展示了使用for实现嵌套循环的例子。

>>> # 创建一个包含元组的列表
>>> prices = [('$5.99', '$4.99'), ('$3.5', '$4.5')]
>>> # 获取元组中的每个价格,以此创建一个一维列表
>>> prices_formatted = [float(x[1:]) for price_group in prices for x in price_group]
>>> print(prices_formatted)
[5.99, 4.99, 3.5, 4.5]
Copy after login

5.替换高阶函数

有的人比较习惯函数式编程,比如使用高阶函数也是这种习惯的表现之一。特别说明一下,高阶函数是那些需要使用输入或输出参数的函数。在 Python 中,常用的高阶函数有 map() 和 filter()。

>>> # 创建一个 integer 类型的列表
>>> integers = [1, 2, 3, 4, 5]
>>> # 使用 map 创建平方数列表
>>> squares_mapped = list(map(lambda x: x*x, integers))
>>> squares_mapped
[1, 4, 9, 16, 25]
>>> # 使用列表推导式创建平方数列表
>>> squares_listcomp = [x*x for x in integers]
>>> squares_listcomp
[1, 4, 9, 16, 25]
>>> # 使用 filter 取得 integers 中的偶数列表
>>> filtered_filter = list(filter(lambda x: x % 2 == 0, integers))
>>> filtered_filter
[2, 4]
>>> # 使用列表推导式取得 integers 中的偶数列表
>>> filterd_listcomp = [x for x in integers if x % 2 == 0]
>>> filterd_listcomp
[2, 4]
Copy after login

从上面的例子可以看出,使用 list 的某些特性比使用高阶函数更具有可读性,而且也能实现较复杂的嵌套结构。

1.不要忘了定义构造函数

有人认为列表推导式很酷炫,是 Python 特有的功能,所以为了炫耀自己的 Python 水平,即使有更好替代方案也要使用它。

>>> # 使用 range 创建列表对象
>>> numbers = [x for x in range(5)]
>>> print(numbers)
[0, 1, 2, 3, 4]
>>> # 以一个字符串为基础,创建一个小写字母的字符列表
>>> letters = [x.lower() for x in 'Smith']
>>> print(letters)
['s', 'm', 'i', 't', 'h']
Copy after login

上述例子中,我们使用了 range 和 string,这两种数据结构都是可迭代的,list()构造函数可以直接使用 iterable 创建一个 list 对象。下面的代码提供了更合理的解决方案。

>>> # 使用 range 创建列表对象
>>> numbers = list(range(5))
>>> print(numbers)
[0, 1, 2, 3, 4]
>>> # 以一个字符串为基础,创建一个小写字母的字符列表
>>> letters = list('Smith'.lower())
>>> print(letters)
['s', 'm', 'i', 't', 'h']
Copy after login

2.不要忘了生成器表达式

在 Python 中,生成器是一种特殊的可迭代对象,它会延迟加载元素,直到被请求才会加载。这在处理大量数据时会非常高效,它能提升存储效率。相比之下,list 对象为了方便计数和索引,一次性创建所有的元素。所以跟生成器相比,在元素个数相同时,list 需要占用更多内存。

我们可以定义一个生成器函数来创建生成器。我们也可以使用下面的语句来创建生成器,这是一种称为生成器表达式的方法。

(expression for item in iterable)
Copy after login

你可能会注意到,除了使用圆括号外,它的语法跟使用 list 的语句很相似。所以需要注意区分。

考虑下面这个例子。我们要计算前一百万个数字的平方和。如果使用 list 来实现,方法如下。

>>> # 创建列表对象 squares
>>> squares = [x*x for x in range(10_000_000)]
>>> # 计算它们的总和
>>> sum(squares)
333333283333335000000
>>> squares.__sizeof__()
81528032
Copy after login
如上所示,list 对象占据 81528032 字节。我们考虑使用 generator 进行相同的操作,代码如下。
>>> # 创建 generator 对象,保存每个数的平方数
>>> squares_gen = (x*x for x in range(10_000_000))
>>> # 计算它们的总和
>>> sum(squares_gen)
333333283333335000000
>>> squares_gen.__sizeof__()
96
Copy after login

跟使用 list 相比,使用 generator 内存开销小得多,只有 96 字节。原因很简单———— generator 不需要获取所有的元素。相反,它只需要获取各个元素在序列中的位置,创建下一个元素并呈现它,而且不必保存在内存中。

结论

本文中,我们整理了 list 应用的一些关键要领。这些该做的和不该做的都非常清晰明了。我估计你会在合适的场景中用到它。下面是本文内容的小结。

Use iteration. There are many types of iterables in Python, and you should master them while mastering the basics (list and tuple).

Use conditional judgment statements. If you are interested in filtering certain elements in iterable, you can study more about conditional judgment.

Use conditional expressions. If you need to selectively obtain certain data, you can use conditional expressions.

Use nested loops. If you want to deal with nested iterables, you can use nested loop structures.

Use list to replace higher-order functionsIn many cases, you can use list to replace higher-order functions.

Don’t forget the constructor of listDefine the constructor of list. You can use iterable to create a list object. If you use iterable directly, this method is recommended.

Don’t forget the generator expression Its syntax is similar to the syntax in list. This is a way to save memory overhead when dealing with large numbers of objects. The difference between list and generator is that list must be created in advance for future indexing and access. If there are many elements, it will consume a lot of memory.

The above is the detailed content of Things to note when using Python list comprehensions. 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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to solve the problem of file name encoding when connecting to FTP server in Python? How to solve the problem of file name encoding when connecting to FTP server in Python? Apr 01, 2025 pm 06:21 PM

When using Python to connect to an FTP server, you may encounter encoding problems when obtaining files in the specified directory and downloading them, especially text on the FTP server...

See all articles