搜索
首页后端开发Python教程PCEP 认证准备的 Python 元组和列表提示

Python Tuples and Lists Tips for PCEP Certification Preparation

立志成为 Python 认证入门级程序员 (PCEP) 需要彻底了解 Python 中的基本数据结构,例如列表和元组。

列表和元组都能够在 Python 中存储对象,但这两种数据结构在用法和语法上存在关键差异。为了帮助您在 PCEP 认证考试中取得好成绩,这里有一些掌握这些数据结构的基本技巧。

1。了解列表和元组的区别
Python 中的列表是可变的,这意味着它们可以在创建后进行修改。另一方面,元组是不可变的,这意味着它们一旦创建就无法更改。这意味着元组的内存需求较低,并且在某些情况下比列表更快,但它们提供的灵活性较低。

列表示例:

# creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# modifying the list by changing the fourth element
numbers[3] = 10
print(numbers)
# output: [1, 2, 3, 10, 5]

元组示例:

# creating a tuple of colors
colors = ("red", "green", "blue")
# trying to modify the tuple by changing the second element
colors[1] = "yellow" 
# this will result in an error as tuples are immutable

2。熟悉列表和元组的语法
列表用方括号 [ ] 表示,而元组则用括号 ( ) 括起来。创建列表或元组就像使用适当的语法向变量声明值一样简单。请记住,元组在初始化后无法修改,因此使用正确的语法至关重要。

列表示例:

# creating a list of fruits
fruits = ["apple", "banana", "orange"]

元组示例:

# creating a tuple of colors
colors = ("red", "green", "blue")

3。了解如何添加和删除项目
列表有各种用于添加和删除项目的内置方法,例如append()、extend() 和remove()。另一方面,元组的内置方法较少,并且没有任何添加或删除项目的方法。因此,如果您需要修改元组,则必须创建一个新元组,而不是更改现有元组。

列表示例:

# adding a new fruit to the end of the list
fruits.append("mango")
print(fruits)
# output: ["apple", "banana", "orange", "mango"]

# removing a fruit from the list
fruits.remove("banana")
print(fruits)
# output: ["apple", "orange", "mango"]

元组示例:

# trying to add a fruit to the end of the tuple
fruits.append("mango")
# this will result in an error as tuples are immutable

# trying to remove a fruit from the tuple
fruits.remove("banana")
# this will also result in an error

4。了解性能差异
由于其不变性,元组通常比列表更快。留意需要存储固定项目集合的场景,并考虑使用元组而不是列表来提高性能。

您可以使用Python中的timeit模块测试列表和元组之间的性能差异。下面是一个比较迭代列表和包含 10 个元素的元组所需时间的示例:

# importing the timeit module
import timeit

# creating a list and a tuple with 10 elements
numbers_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
numbers_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# testing the time it takes to iterate through the list
list_time = timeit.timeit('for num in numbers_list: pass', globals=globals(), number=100000)
print("Time taken for list: ", list_time)
# output: Time taken for list: 0.01176179499915356 seconds

# testing the time it takes to iterate through the tuple
tuple_time = timeit.timeit('for num in numbers_tuple: pass', globals=globals(), number=100000)
print("Time taken for tuple: ", tuple_time)
# output: Time taken for tuple: 0.006707087000323646 seconds

如您所见,迭代元组比迭代列表稍快。

5。了解列表和元组的适当用例
列表适合存储可能随时间变化的项目集合,因为它们可以轻松修改。相比之下,元组非常适合需要保持不变的项目的恒定集合。例如,虽然列表可能适合可以更改的杂货清单,但元组更适合存储一周中的几天,因为它们保持不变。

列表示例:

# creating a list of groceries
grocery_list = ["milk", "bread", "eggs", "chicken"]
# adding a new item to the grocery list
grocery_list.append("bananas")

元组示例:

# creating a tuple of weekdays
weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
# trying to add a new day to the tuple
weekdays.append("Saturday")
# this will result in an error as tuples cannot be modified after creation

6。注意内存使用
由于其灵活性,列表比元组消耗更多的内存,而元组由于其不变性而占用更少的空间。在处理大型数据集或内存密集型应用程序时,这一点尤其重要。

可以使用Python中的sys模块来检查变量的内存使用情况。以下是比较列表和具有一百万个元素的元组的内存使用情况的示例:

# importing the sys module
import sys

# creating a list with one million elements
numbers_list = list(range(1000000))
# checking the memory usage of the list
list_memory = sys.getsizeof(numbers_list)
print("Memory usage for list: ", list_memory)
# output: Memory usage for list:  9000112 bytes

# creating a tuple with one million elements
numbers_tuple = tuple(range(1000000))
# checking the memory usage of the tuple
tuple_memory = sys.getsizeof(numbers_tuple)
print("Memory usage for tuple: ", tuple_memory)
# output: Memory usage for tuple: 4000072 bytes

您可以看到,与列表相比,元组消耗的内存更少。

7。知道如何迭代列表和元组
列表和元组都可以通过使用循环进行迭代,但由于它们的不变性,元组可能会稍微快一些。另请注意,列表可以存储任何类型的数据,而元组只能包含可哈希元素。这意味着元组可以用作字典键,而列表则不能。

列表示例:

# creating a list of numbers
numbers = [1, 2, 3, 4, 5]
# iterating through the list and checking if a number is present
for num in numbers:
    if num == 3:
        print("Number 3 is present in the list")
# output: Number 3 is present in the list

元组示例:

# creating a tuple of colors
colors = ("red", "green", "blue")
# iterating through the tuple and checking if a color is present
for color in colors:
    if color == "yellow":
        print("Yellow is one of the colors in the tuple")
# this will not print anything as yellow is not present in the tuple

8。熟悉内置函数和操作
虽然与元组相比,列表具有更多的内置方法,但这两种数据结构都具有一系列您应该熟悉 PCEP 考试的内置函数和运算符。其中包括 len()、max() 和 min() 等函数,以及 in 和 not in 等运算符,用于检查某个项目是否在列表或元组中。

列表示例:

# creating a list of even numbers
numbers = [2, 4, 6, 8, 10]
# using the len() function to get the length of the list
print("Length of the list: ", len(numbers))
# output: Length of the list: 5
# using the in and not in operators to check if a number is present in the list
print(12 in numbers)
# output: False
print(5 not in numbers)
# output: True

元组示例:

# creating a tuple of colors
colors = ("red", "green", "blue")
# using the max() function to get the maximum element in the tuple
print("Maximum color: ", max(colors))
# output: Maximum color: red
# using the in and not in operators to check if a color is present in the tuple
print("yellow" in colors)
# output: False
print("green" not in colors)
# output: False

通过了解列表和元组的差异、适当的用例以及语法,您将为 PCEP 考试做好充分准备。请记住在不同场景中练习使用这些数据结构,以巩固您的知识并增加通过考试的机会。请记住,熟能生巧!

以上是PCEP 认证准备的 Python 元组和列表提示的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何解决Linux终端中查看Python版本时遇到的权限问题?如何解决Linux终端中查看Python版本时遇到的权限问题?Apr 01, 2025 pm 05:09 PM

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

我如何使用美丽的汤来解析HTML?我如何使用美丽的汤来解析HTML?Mar 10, 2025 pm 06:54 PM

本文解释了如何使用美丽的汤库来解析html。 它详细介绍了常见方法,例如find(),find_all(),select()和get_text(),以用于数据提取,处理不同的HTML结构和错误以及替代方案(SEL)

python对象的序列化和避难所化:第1部分python对象的序列化和避难所化:第1部分Mar 08, 2025 am 09:39 AM

Python 对象的序列化和反序列化是任何非平凡程序的关键方面。如果您将某些内容保存到 Python 文件中,如果您读取配置文件,或者如果您响应 HTTP 请求,您都会进行对象序列化和反序列化。 从某种意义上说,序列化和反序列化是世界上最无聊的事情。谁会在乎所有这些格式和协议?您想持久化或流式传输一些 Python 对象,并在以后完整地取回它们。 这是一种在概念层面上看待世界的好方法。但是,在实际层面上,您选择的序列化方案、格式或协议可能会决定程序运行的速度、安全性、维护状态的自由度以及与其他系

如何使用TensorFlow或Pytorch进行深度学习?如何使用TensorFlow或Pytorch进行深度学习?Mar 10, 2025 pm 06:52 PM

本文比较了Tensorflow和Pytorch的深度学习。 它详细介绍了所涉及的步骤:数据准备,模型构建,培训,评估和部署。 框架之间的关键差异,特别是关于计算刻度的

Python中的数学模块:统计Python中的数学模块:统计Mar 09, 2025 am 11:40 AM

Python的statistics模块提供强大的数据统计分析功能,帮助我们快速理解数据整体特征,例如生物统计学和商业分析等领域。无需逐个查看数据点,只需查看均值或方差等统计量,即可发现原始数据中可能被忽略的趋势和特征,并更轻松、有效地比较大型数据集。 本教程将介绍如何计算平均值和衡量数据集的离散程度。除非另有说明,本模块中的所有函数都支持使用mean()函数计算平均值,而非简单的求和平均。 也可使用浮点数。 import random import statistics from fracti

用美丽的汤在Python中刮擦网页:搜索和DOM修改用美丽的汤在Python中刮擦网页:搜索和DOM修改Mar 08, 2025 am 10:36 AM

该教程建立在先前对美丽汤的介绍基础上,重点是简单的树导航之外的DOM操纵。 我们将探索有效的搜索方法和技术,以修改HTML结构。 一种常见的DOM搜索方法是EX

哪些流行的Python库及其用途?哪些流行的Python库及其用途?Mar 21, 2025 pm 06:46 PM

本文讨论了诸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和请求等流行的Python库,并详细介绍了它们在科学计算,数据分析,可视化,机器学习,网络开发和H中的用途

如何使用Python创建命令行接口(CLI)?如何使用Python创建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指导Python开发人员构建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等库详细介绍,强调输入/输出处理,并促进用户友好的设计模式,以提高CLI可用性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),