Python 元组

元组是不同数据类型的元素的不可变(不可改变)集合。这是一个有序集合,因此它保留了元素定义的顺序。

元组由括号()中的元素定义,用逗号分隔。 下面声明一个元组类型变量。

Example: Tuple Variable Declaration

tpl=() # empty tuple
print(tpl)

names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple
print(names)

nums = (1, 2, 3, 4, 5) # int tuple
print(nums)

employee=(1, 'Steve', True, 25, 12000)  # heterogeneous data tuple
print(employee) 

Output:

()
('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000) 

但是,不必将元组元素括在括号中。元组对象可以包括由逗号分隔的元素,没有括号。

Example: Tuple Variable Declaration

names = 'Jeff', 'Bill', 'Steve', 'Yash' # string tuple
print(names)

nums = 1, 2, 3, 4, 5 # int tuple
print(nums)

employee=1, 'Steve', True, 25, 12000  # heterogeneous data tuple
print(employee) 

Output:

('Jeff', 'Bill', 'Steve', 'Yash')
(1, 2, 3, 4, 5)
(1, 'Steve', True, 25, 12000) 

除非后跟逗号,否则元组不能用单个元素声明。

Example: Tuple Variable Declaration

names = ('Jeff') # considered as string type
print(names)
print(type(names))

names = ('Jeff',) # tuple with single element
print(names)
print(type(names)) 

Output:

'Jeff'
<class 'string'>
(Jeff)
<class 'tuple'> 

访问元组元素

元组中的每个元素都由方括号[]中的索引访问。索引以零开始,以(元素数- 1)结束,如下所示。

Example: Access Tuple Elements using Indexes

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[0]) # prints 'Jeff'
print(names[1]) # prints 'Bill'
print(names[2]) # prints 'Steve'
print(names[3]) # prints 'Yash'

nums = (1, 2, 3, 4, 5) 
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5 

Output:

Jeff
Bill
Steve
Yash
1
2
5 

元组也支持负索引,与列表类型相同。第一个元素的负指数从-number of elements开始,最后一个元素以-1 结束。

Example: Negative Indexing

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print(names[-4]) # prints 'Jeff'
print(names[-3]) # prints 'Bill'
print(names[-2]) # prints 'Steve'
print(names[-1]) # prints 'Yash' 

Output:

Jeff
Bill
Steve
Yash 

如果指定索引处的元素不存在,则将引发错误“索引超出范围”。

>>> names[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range 

元组元素可以被解包并分配给变量,如下所示。但是,变量的数量必须与元组中元素的数量相匹配;否则,将引发错误。

Example: Access Tuple Elements using Indexes

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
a, b, c, d = names # unpack tuple
print(a, b, c, d) 

Output:

Jeff Bill Steve Yash 

更新或删除元组元素

元组是不可更改的。因此,一旦创建了元组,任何试图改变其内容的操作都是不允许的。例如,试图修改或删除names元组的元素将导致错误。

>>> names = ('Jeff', 'Bill', 'Steve', 'Yash') 
>>> names[0] = 'Swati'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

>>> del names[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object doesn't support item deletion 

但是,您可以使用del关键字删除整个元组。

>>> del names

元组类

元组的基础类型是元组类。使用type()功能检查变量的类型。

Example: Tuple Variable Declaration

names = ('Jeff', 'Bill', 'Steve', 'Yash') 
print('names type: ', type(names))

nums = (1,2,3,4,5) 
print('nums type: ', type(nums)) 

Output:

names type: <class 'tuple'>
nums type: <class 'tuple'> 

tuple()构造器用于将任何可迭代类型转换为元组类型。

Example: Tuple Variable Declaration

tpl = tuple('Hello') # converts string to tuple
print(tpl)
tpl = tuple([1,2,3,4,5]) # converts list to tuple
print(tpl)
tpl = tuple({1,2,3,4,5}) # converts set to tuple
print(tpl)
tpl = tuple({1:"One",2:"Two"}) # converts dictionary to tuple
print(tpl) 

Output:

('H','e','l','l','o')
(1,2,3,4,5)
(1,2,3,4,5)
(1,2) 

元组运算

像字符串一样,元组对象也是一个序列。因此,用于字符串的运算符也可用于元组。

操作员例子
+ 运算符返回包含第一个和第二个元组对象的所有元素的元组。
>>> t1=(1,2,3)
>>> t2=(4,5,6)         
>>> t1+t2              
(1, 2, 3, 4, 5, 6) 
>>> t2+(7,)            
(4, 5, 6, 7)

|
| ***** 运算符连接同一个元组的多个副本。 |

>>> t1=(1,2,3)
>>> t1*4                             
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)

|
| [] 运算符返回给定索引处的项目。负索引从右侧开始计算位置。 |

>>> t1=(1,2,3,4,5,6)     
>>> t1[3]                
4                        
>>> t1[-2]               
5

|
| [:] 运算符返回由两个索引操作数指定的范围内的项目,这两个索引操作数由:符号分隔。
如果省略第一个操作数,范围从零开始。 如果省略第二个操作数,范围将上升到元组的末尾。 |

>>> t1=(1,2,3,4,5,6) 
>>> t1[1:3]              
(2, 3)                   
>>> t1[3:]               
(4, 5, 6)                
>>> t1[:3]               
(1, 2, 3)

|
| 如果给定元组中存在某项,则运算符中的返回真。 |

>>> t1=(1,2,3,4,5,6) 
>>> 5 in t1
True                
>>> 10 in t1 
False

|
| 如果给定元组中不存在某项,则不在运算符中的返回真。 |

>>> t1=(1,2,3,4,5,6) 
>>> 4 not in t1 
False                    
>>> 10 not in t1
True

|

原创文章,作者:PIHFQ,如若转载,请注明出处:https://www.506064.com/n/329809.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
PIHFQ的头像PIHFQ
上一篇 2025-01-14 18:55
下一篇 2025-01-14 18:55

相关推荐

  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29

发表回复

登录后才能评论