教程集 www.jiaochengji.com
教程集 >  Python编程  >  Python入门  >  正文 python3中的元组

python3中的元组

发布时间:2021-12-15   编辑:jiaochengji.com
教程集为您提供python3中的元组等资源,欢迎您收藏本站,我们将为您提供最新的python3中的元组资源

Python3 元组

Python 的元组与列表类似,不同之处在于元组的元素不能修改。

元组使用小括号,列表使用方括号。

元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。

如下实例

<pre class="brush:html;toolbar:false">tup1 = ('Google', 'W3CSchool', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d";</pre>

创建空元组

<pre class="brush:html;toolbar:false">tup1 = ();</pre>

元组中只包含一个元素时,需要在元素后面添加逗号

<pre class="brush:html;toolbar:false">tup1 = (50,);</pre>

元组与字符串类似,下标索引从0开始,可以进行截取,组合等。

访问元组

元组可以使用下标索引来访问元组中的值,如下实例:

<pre class="brush:html;toolbar:false">#!/usr/bin/python3 tup1 = ('Google', 'W3CSchool', 1997, 2000) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5])</pre>

以上实例输出结果:

<pre class="brush:html;toolbar:false">tup1[0]:  Google tup2[1:5]:  (2, 3, 4, 5)</pre>

修改元组

元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:

<pre class="brush:html;toolbar:false">#!/usr/bin/python3 tup1 = (12, 34.56); tup2 = ('abc', 'xyz') # 以下修改元组元素操作是非法的。 # tup1[0] = 100 # 创建一个新的元组 tup3 = tup1   tup2; print (tup3)</pre>

以上实例输出结果:

<pre class="brush:html;toolbar:false">(12, 34.56, 'abc', 'xyz')</pre>

删除元组

元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:

<pre class="brush:html;toolbar:false">#!/usr/bin/python3 tup = ('Google', 'W3CSchool', 1997, 2000) print (tup) del tup; print ("删除后的元组 tup : ") print (tup)</pre>

以上实例元组被删除后,输出变量会有异常信息,输出如下所示:

<pre class="brush:html;toolbar:false">删除后的元组 tup :  Traceback (most recent call last):   File "test.py", line 8, in <module>     print (tup) NameError: name 'tup' is not defined</pre>

您可能感兴趣的文章:
python3中的元组
讲解Python3内置模块之json编码解码方法
2019年python学3还是2
python2和python3中print有什么区别
python2和3print的区别
python中什么是序列
3种算法实现Python3数组的旋转
python3如何排序
linux如何安装python3
python数据类型是什么

上一篇:Python3中的字典 下一篇:Python3中的列表
[关闭]
~ ~