教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 python列表推导式是什么?

python列表推导式是什么?

发布时间:2021-12-30   编辑:jiaochengji.com
教程集为您提供python列表推导式是什么?等资源,欢迎您收藏本站,我们将为您提供最新的python列表推导式是什么?资源

乍一看到列表推导式你可能会感到疑惑。它们是一种创建和使用列表的简洁方式。理解列表推导式是有用的,因为你可能在其他人的代码里看到列表推导式。下面来了解下列表推导式吧。

数字列表的推导式

回顾之前学过的知识,我们可以创建一个包含前10个数字的列表,如下所示:

<pre class="brush:php;toolbar:false">squares = [] for number in range(1,11):     new_square = number**2     squares.append(new_square) for square in squares:     print(square)</pre>

<span style="color: rgb(85, 85, 85); font-family: "Classic Grotesque W01", "Avenir Next", "Segoe UI", "Helvetica Neue", Arial, "Hiragino Sans GB", "PingFang SC", "Heiti SC", "Microsoft YaHei UI", "Microsoft YaHei", "Source Han Sans", sans-serif; font-size: 16px; white-space: normal; background-color: rgb(255, 255, 255);">上述代码中我们实现了创建包含10个数字的列表,对每个数字作平方操作并将它们存储进新的数组的功能。代码略显冗长,我们可以省略 for 循环中的 new_square 参数,简化代码。使用列表推导式就可以进一步简化代码,如下所示:</span>

<pre class="brush:php;toolbar:false">squares = [number**2 for number in range(1,11)] for square in squares:     print(square)</pre>

平方操作和生成新列表的过程都浓缩进了一行代码。你是不是已经晕头转向了,让我们来看看这行代码发生了什么。

首先我们定义了一个列表,名字为 squares 。

接下来看看列表中括号中的代码:

<pre class="brush:php;toolbar:false">for number in range(1, 11)</pre>

它在1-10之间创建一个循环,把每个数字存储到变量 number 中。接下来我们看一看对每次循环中的 number 作了哪些操作。

 number**2

每个 number 都作了平方操作,并将结果存储在了定义好的队列中。我们可以用如下语言来阅读这行代码:

<pre class="brush:php;toolbar:false">squares = [raise number to the second power, for each number in the range 1-10]、</pre>

其他例子

上个例子是对数字作平方操作,下列代码是对数字作乘操作,仔细阅读代码,体会数字列表表达式的用法。

<pre class="brush:php;toolbar:false"># Make an empty list that will hold the even numbers. evens = [] # Loop through the numbers 1-10, double each one, and add it to our list. for number in range(1,11):     evens.append(number*2)      # Show that our list is correct: for even in evens:     print(even)</pre>

非数字列表的推导式

我们也可以在非数字列表中运用推导式。在下面的例子中,我们会创建一个非数字列表,然后利用推导式生成一个新的列表。不运用推导式的源代码如下所示:

<pre class="brush:php;toolbar:false"># Consider some students. students = ['bernice', 'aaron', 'cody'] # Let's turn them into great students. great_students = [] for student in students:     great_students.append(student.title()   " the great!") # Let's greet each great student. for great_student in great_students:     print("Hello, "   great_student)</pre>

我们想写下如下所示的推导式:

great_students = [add 'the great' to each student, for each student in the list of students]

代码如下所示:

<pre class="brush:php;toolbar:false"># Consider some students. students = ['bernice', 'aaron', 'cody'] # Let's turn them into great students. great_students = [student.title()   " the great!" for student in students] # Let's greet each great student. for great_student in great_students:     print("Hello, "   great_student)</pre>

您可能感兴趣的文章:
python怎么对列表中元素去重复
python列表推导式是什么?
python中的list是什么
python中的-1是什么意思
python3.6有什么优势
零基础学python需要多久
Python之从列表推导到zip()函数的五种技巧
python为什么要装32位的
python u是什么意思
python怎么检查元素是否在列表中存在

[关闭]
~ ~