【Python】元组和命名元组

命名元组是在元组基础上的一个扩展,这里先介绍一下何为元组

1. 元组

元组长的很像列表,但是却是用圆括号而不是方括号来标识。定义元组后,如果想要访问其中的元素,也可像访问列表中的值一样使用索引访问。

1.创建元组

代码如下

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

创建空元组

tup1 = ();

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

tup1 = (50,);

2.访问元祖

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
 
print "tup1[0]: ", tup1[0]
print "tup2[1:5]: ", tup2[1:5]
# 以上实例输出结果:
# tup1[0]:  physics
# tup2[1:5]:  [2, 3, 4, 5]

3.修改元组

元组是不能够进行修改的,但是能够对两个元组进行拼接。

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
 
# 以下修改元组元素操作是非法的。
# tup1[0] = 100;
 
# 创建一个新的元组
tup3 = tup1 + tup2;
print tup3;
#以上实例输出结果:
#(12, 34.56, 'abc', 'xyz')

4.删除元组

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

tup = ('physics', 'chemistry', 1997, 2000);
 
print tup;
del tup;
print "After deleting tup : "
print tup;
 
 
#以上实例元组被删除后,输出变量会有异常信息,输出如下所示:
#('physics', 'chemistry', 1997, 2000)
#After deleting tup :
#Traceback (most recent call last):
#  File "test.py", line 9, in <module>
#    print tup;
#NameError: name 'tup' is not defined[/code]

5.元组内置函数

Python元组包含了以下内置函数
1、cmp(tuple1, tuple2):比较两个元组元素。
2、len(tuple):计算元组元素个数。
3、max(tuple):返回元组中元素最大值。
4、min(tuple):返回元组中元素最小值。
5、tuple(seq):将列表转换为元组

2.命名元组

元组是以下标取值的,但是命名元组能为元组中每一个值定义一个对应的名称,像字典一样根据名称取值。

命名元祖:collections模块中的namedtuple函数

#namedtuple:接受两个参数,第一个创建的类型名称,第二个则是值名称列表

from collections import namedtuple

Student = namedtuple('Student', ['name', 'age', 'gender'])
s = Student ('小明', 13, '男')
print(s.name)
print(s.gender)

和字典有些类似,但是只需要定义一次特性,后续使用不需要再定义key。

发布了81 篇原创文章 · 获赞 161 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_34659777/article/details/104307137