通过代码实例展示Python中列表生成式的用法
1 平方列表
如果你想创建一个包含1到10的平方的列表,你可以这样做:
squares = [] for x in range(10): squares.append(x**2)
这是一个简单的例子,但是使用列表生成式可以更简洁地创建这个列表。
squares = [x**2 for x in range(10)]
这个最简单的列表生成式由方括号开始,方括号内部先是一个表达式,其后跟着一个for语句。列表生成式总是返回一个列表。
2 整除3的数字列表
通常,你可能这样写:
numbers = [] for x in range(100): if x % 3 == 0: numbers.append(x)
你可以在列表生成式里包含一个if语句,来有条件地为列表添加项。为了创建一个包含0到100间能被3整除的数字列表,可以使用列表推导式:
numbers = [x for x in range(100) if x % 3 == 0]
3 找出质数
这通常要使用好几行代码来实现。
noprimes = [] for i in range(2, 8): for j in range(i*2, 50, i): noprimes.append(j) primes = [] for x in range(2, 50): if x not in noprimes: primes.append(x)
不过,你可以使用两个列表生成式来简化代码。
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes]
第一行代码在一个列表生成式里使用了多层for循环。第一个循环是外部循环,第二个循环是是内部循环。为了找到质数,我们首先找到一个非质数的列表。通过找出2-7的倍数来产生这个非质数列表。然后我们循环遍历数字并查看每个数字是否在非质数列表。
修正:正如reddit上的shoyer指出的,使用集合(set)来查找noprimes(代码里的属性参数,译者注)效率更高。由于noprimes应该只包含唯一的值,并且我们频繁地去检查一个值是否存在,所以我们应该使用集合。集合的使用语法和列表的使用语法类似,所以我们可以这样使用:
noprimes = set(j for i in range(2, 8) for j in range(i*2, 50, i)) primes = [x for x in range(2, 50) if x not in noprimes]
4 嵌套列表降维
假设你有一个列表的列表(列表里包含列表)或者一个矩阵,
matrix = [[0,1,2,3], [4,5,6,7], [8,9,10,11]]
并且你想把它降维到一个一维列表。你可以这样做:
flattened = [] for row in matrix: for i in row: flattened.append(i)
使用列表生成式:
flattened = [i for row in matrix for i in row]
这使用了两个for循环去迭代整个矩阵。外层(第一个)循环按行迭代,内部(第二个)循环对该行的每个项进行迭代。
5 模拟多个掷硬币事件
假设需要模拟多次掷硬币事件,其中0表示正面,1表示反面,你可以这样编写代码:
from random import random results = [] for x in range(10): results.append(int(round(random())))
或者使用列表生成式使代码更简洁:
from random import random results = [int(round(random())) for x in range(10)]
这里使用了range函数循环了10次。每一次我们都把random()的输出进行四舍五入。因为random()函数返回一个0到1的浮点数,所以对输出进行四舍五入就会返回0或者1。Round()函数返回一个浮点型数据,使用int()将其转为整型并添加到列表里。
6 移除句子中的元音字母
假设你有一个句子,
sentence = 'Your mother was a hamster'
并且你想移除所有的元音字母。我们可以使用几行代码轻易做到:
vowels = 'aeiou' non_list = [] for l in sentence: if not l in vowels: non_list.append(l) nonvowels = ''.join(non_list)
或者你可以使用列表生成式简化它:
vowels = 'aeiou' nonvowels = ''.join([l for l in sentence if not l in vowels])
这个例子使用列表生成式创建一个字母列表,字母列表的字母来自sentence句子的非元音字母。然后我们把生成的列表传给join()函数去转换为字符串。
修正:正如reddit上的iamadogwhatisthis提出的,这个例子不需要列表生成式。使用生成器(generator)更好:
vowels = 'aeiou' nonvowels = ''.join(l for l in sentence if not l in vowels)
注意,这里去掉了方括号。这是因为join函数接收任意可迭代的数据,包括列表或者生成器。这个没有方括号的语法使用了生成器。这产生(与列表生成式)同样的结果,相对于之前把所有条目包装成一个列表,生成器在我们遍历时才产生相应的条目。这可以使我们不必保存整个列表到内存,并且这对于处理大量数据更有效率。
7 获取目录里的文件名列表
下面的代码将会遍历my_dir目录下的文件,并在files里追加每个以txt为后缀的文件名。
import os files = [] for f in os.listdir('./my_dir'): if f.endswith('.txt'): files.append(f)
这同样可以使用列表生成式简化代码:
import os files = [f for f in os.listdir('./my_dir') if f.endswith('.txt')]
或者你可以获取一个相对路径的列表:
import os files = [os.path.join('./my_dir', f) for f in os.listdir('./my_dir') if f.endswith('.txt')]
感谢reddit上的rasbt提供。
8 将csv文件读取为字典列表
我们常常需要读取和处理csv文件的数据。处理csv数据的一个最有用的方法就是把它转换为一个字典列表。
import csv data = [] for x in csv.DictReader(open('file.csv', 'rU')): data.append(x)
你可以使用列表生成式快速实现:
import csv data = [ x for x in csv.DictReader(open('file.csv', 'rU'))]
DictReader类将会自动地使用csv文件的第一行作为字典的key属性名。DictReader类返回一个将会遍历csv文件所有行的对象。这个文件对象通过open()函数产生。我们提供了open()两个参数–第一个是csv文件名,第二个是模式。在这例子,‘rU'有两个意思。想往常一样,‘r'表示以读模式打开文件。‘U'表明我们将会接受通用换行符–‘n',‘r'和‘rn'。
感谢reddit上的blacwidonsfw提供。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
