个性化阅读
专注于IT技术分析

Python列表理解用法详细介绍

本文概述

Python以鼓励开发人员和程序员编写高效, 易懂且几乎易读的代码而闻名。该语言最独特的方面之一是python列表和列表压缩功能, 可以在一行代码中使用它来构造强大的功能。列表推导用于从其他可迭代对象(如元组, 字符串, 数组, 列表等)创建新列表。

列表推导由包含表达式的方括号组成, 该表达式针对每个元素以及用于循环遍历每个元素的for循环执行。

语法如下:

newList = [如果条件, 则为oldList中元素的expression(element)]

迭代列表

有多种方法可以遍历列表。但是, 最常见的方法是使用对于循环。让我们看下面的例子:

Python3

# Empty list List = [] # Traditional approach of iterating for character in 'Geeks 4 Geeks!' : List .append(character) # Display list print ( List )

输出如下:

[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ”, ‘4’, ”, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’ , ‘!’]

上面是对列表, 字符串, 元组等进行迭代的传统方法的实现。现在列表理解可以完成相同的任务, 并使程序更简单。

列表推导将使用for循环的传统迭代方法转换为简单的公式, 从而使其易于使用。下面是使用列表理解迭代列表, 字符串, 元组等的方法。

Python3

# Using list comprehension to iterate through loop List = [character for character in 'Geeks 4 Geeks!' ] # Displaying list print ( List )

输出如下:

[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ”, ‘4’, ”, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’ , ‘!’]

下面是一些示例, 这些示例描述了列表推导的使用, 而不是传统的通过可迭代对象进行迭代的方法:

示例1:显示从1到10的数字的平方。

Python3

# Getting square of numbers from 1 to 10 squares = [n * * 2 for n in range ( 1 , 11 )] # Display square of numbers print (squares)

输出如下:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

示例2:显示随机数列表中的偶数元素。

Python3

# List of random numbers List = [ 4 , 8 , 12 , 7 , 8 , 63 , 99 ] # Displaying only even numbers print ([n for n in List if n % 2 = = 0 ])

输出如下:

[4, 8, 12, 8]

示例3:切换字符串中每个字符的大小写。

Python3

# Initializing string string = 'Geeks4Geeks!' # Toggle case of each character List = [s.swapcase() for s in string] # Display list print ( List )

输出如下:

[‘g’, ‘E’, ‘E’, ‘K’, ‘S’, ‘4’, ‘g’, ‘E’, ‘E’, ‘K’, ‘S’, ‘!’]

示例4:反转元组中的每个字符串。

Python3

# Initializing tuple Tuple = ( 'Geeks' , 'for' , 'Geeks' ) # Reverse each string in tuple List = [string[:: - 1 ] for string in Tuple ] # Display list print ( List )

输出如下:

['skeeG', 'rof', 'skeeG']

示例5:显示列表中所有奇数元素的数字总和。

Python3

# Explicit function def digitSum(n): dsum = 0 for ele in str (n): dsum + = int (ele) return dsum # Initializing list List = [ 367 , 111 , 562 , 945 , 6726 , 873 ] # Using the function on odd elements of the list newList = [digitSum(i) for i in List if i & 1 ] # Displaying new list print (newList)

输出如下:

[16, 3, 18, 18]

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python列表理解用法详细介绍

评论 抢沙发

评论前必须登录!