元组是 Python 中重要的数据结构,提供了一种存储有序且不可变数据集合的便捷方法。
在本博客中,您将了解有关 Python 中元组的所有内容,包括创建、切片、方法等等。
让我们直接开始吧!?
Python 中的元组
元组是数据项的有序集合。在元组中,您可以将多个项目存储在单个变量中。
元组是不可变的,即创建后您无法更改它们。
创建元组
元组使用圆括号 () 定义,项目之间用逗号分隔。
元组可以包含不同数据类型的项。
例如:
tuple1 = (1,2,36,3,15) tuple2 = ("Red", "Yellow", "Blue") tuple3 = (1, "John",12, 5.3) print(tuple1) # (1, 2, 36, 3, 15) print(tuple2) # ('Red', 'Yellow', 'Blue') print(tuple3) # (1, 'John', 12, 5.3)
单项元组
要创建包含一项的元组,请在该项后面添加一个逗号。如果没有逗号,Python 会将其视为整数类型。
例如:
tuple1 = (1) # This is an integer. print(type(tuple1)) # <class> tuple2 = (1,) # This is a tuple. print(type(tuple2)) # <class> </class></class>
元组长度
您可以使用 len() 函数查找元组的长度(元组中的项目数)。
例如:
tuple1 = (1,2,36,3,15) lengthOfTuple = len(tuple1) print(lengthOfTuple) # 5
访问元组项
您可以使用索引访问元组项/元素。每个元素都有其唯一的索引。
第一个元素的索引从 0 开始,第二个元素的索引从 1 开始,依此类推。
例如:
fruits = ("Orange", "Apple", "Banana") print(fruits[0]) # Orange print(fruits[1]) # Apple print(fruits[2]) # Banana
您还可以从元组末尾访问元素(-1 表示最后一个元素,-2 表示倒数第二个元素,依此类推),这称为负索引。
例如:
fruits = ("Orange", "Apple", "Banana") print(fruits[-1]) # Banana print(fruits[-2]) # Apple print(fruits[-3]) # Orange # for understanding, you can consider this as fruits[len(fruits)-3]
检查元组中是否存在某个项目
您可以使用 in 关键字检查元组中是否存在某个元素。
示例1:
fruits = ("Orange", "Apple", "Banana") if "Orange" in fruits: print("Orange is in the tuple.") else: print("Orange is not in the tuple.") #Output: Orange is in the tuple.
示例2:
numbers = (1, 57, 13) if 7 in numbers: print("7 is in the tuple.") else: print("7 is not in the tuple.") # Output: 7 is not in the tuple.
元组切片
您可以通过给出开始、结束和跳转(跳过)参数来获取一系列元组项目。
语法:
tupleName[start : end : jumpIndex]
注意:跳转索引是可选的。
示例1:
# Printing elements within a particular range numbers = (1, 57, 13, 6, 18, 54) # using positive indexes(this will print the items starting from index 2 and ending at index 4 i.e. (5-1)) print(numbers[2:5]) # using negative indexes(this will print the items starting from index -5 and ending at index -3 i.e. (-2-1)) print(numbers[-5:-2])
输出:
(13, 6, 18) (57, 13, 6)
示例2:
当没有提供结束索引时,解释器将打印直到末尾的所有值。
# Printing all elements from a given index to till the end numbers = (1, 57, 13, 6, 18, 54) # using positive indexes print(numbers[2:]) # using negative indexes print(numbers[-5:])
输出:
(13, 6, 18, 54) (57, 13, 6, 18, 54)
示例3:
当没有提供开始索引时,解释器会打印从开始到提供的结束索引的所有值。
# Printing all elements from start to a given index numbers = (1, 57, 13, 6, 18, 54) #using positive indexes print(numbers[:4]) #using negative indexes print(numbers[:-2])
输出:
(1, 57, 13, 6) (1, 57, 13, 6)
示例 4:
您可以通过给出跳转索引来打印替代值。
# Printing alternate values numbers = (1, 57, 13, 6, 18, 54) # using positive indexes(here start and end indexes are not given and 2 is jump index.) print(numbers[::2]) # using negative indexes(here start index is -2, end index is not given and 2 is jump index.) print(numbers[-2::2])
输出:
(1, 13, 18) (18)
操作元组
元组不可变,因此无法添加、删除或更改项目。但是,您可以将元组转换为列表,修改列表,然后将其转换回元组。
例如:
tuple1 = (1,2,36,3,15) tuple2 = ("Red", "Yellow", "Blue") tuple3 = (1, "John",12, 5.3) print(tuple1) # (1, 2, 36, 3, 15) print(tuple2) # ('Red', 'Yellow', 'Blue') print(tuple3) # (1, 'John', 12, 5.3)
连接元组
您可以使用运算符连接两个元组。
例如:
tuple1 = (1) # This is an integer. print(type(tuple1)) # <class> tuple2 = (1,) # This is a tuple. print(type(tuple2)) # <class> </class></class>
输出:
tuple1 = (1,2,36,3,15) lengthOfTuple = len(tuple1) print(lengthOfTuple) # 5
元组方法
Tuple 有以下内置方法:
数数()
此方法返回元素在元组中出现的次数。
语法:
fruits = ("Orange", "Apple", "Banana") print(fruits[0]) # Orange print(fruits[1]) # Apple print(fruits[2]) # Banana
例如:
fruits = ("Orange", "Apple", "Banana") print(fruits[-1]) # Banana print(fruits[-2]) # Apple print(fruits[-3]) # Orange # for understanding, you can consider this as fruits[len(fruits)-3]
指数()
此方法返回元组中给定元素的第一次出现。
注意:如果在元组中找不到该元素,此方法会引发 ValueError。
例如:
fruits = ("Orange", "Apple", "Banana") if "Orange" in fruits: print("Orange is in the tuple.") else: print("Orange is not in the tuple.") #Output: Orange is in the tuple.
您可以为搜索指定起始索引。例如:
numbers = (1, 57, 13) if 7 in numbers: print("7 is in the tuple.") else: print("7 is not in the tuple.") # Output: 7 is not in the tuple.
今天就这些。
希望对您有帮助。
感谢您的阅读。
我在学习 Python 语言时创建了详细的 Python 笔记,而且仅需 1 美元!在这里获取它们:立即下载
有关更多此类内容,请点击此处。
在 X(Twitter) 上关注我,获取日常 Web 开发技巧。
继续编码!!
以上是掌握 Python 中的元组:综合指南的详细内容。更多信息请关注PHP中文网其他相关文章!

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的关键特性包括:1.语法简洁易懂,适合初学者;2.动态类型系统,提高开发速度;3.丰富的标准库,支持多种任务;4.强大的社区和生态系统,提供广泛支持;5.解释性,适合脚本和快速原型开发;6.多范式支持,适用于各种编程风格。

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies


热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

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