search
HomeBackend DevelopmentPython Tutorial通过代码实例展示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提供。

Statement
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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),