📜  Python元组

📅  最后修改于: 2020-12-23 05:15:25             🧑  作者: Mango


元组是有序且不可变的对象的集合。元组是序列,就像列表一样。元组和列表之间的区别在于,不能像列表一样更改元组,并且元组使用括号,而列表使用方括号。

创建元组就像放置不同的逗号分隔值一样简单。您也可以选择将这些逗号分隔的值放在括号之间。例如-

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

空元组写为两个不包含任何内容的括号-

tup1 = ();

要编写包含单个值的元组,即使只有一个值,您也必须包含逗号-

tup1 = (50,);

像字符串索引一样,元组索引从0开始,并且可以对其进行切片,连接等。

访问元组中的值

要访问元组中的值,请使用方括号与一个或多个索引一起切片,以获取该索引处可用的值。例如-

现场演示

#!/usr/bin/python

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]

更新元组

元组是不可变的,这意味着您无法更新或更改元组元素的值。您可以使用部分现有元组来创建新元组,如以下示例所示:

现场演示

#!/usr/bin/python

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;

执行以上代码后,将产生以下结果-

(12, 34.56, 'abc', 'xyz')

删除元组元素

无法删除单个元组元素。当然,将另一个元组与不想要的元素丢弃在一起并没有错。

要显式删除整个元组,只需使用del语句。例如-

现场演示

#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;

这将产生以下结果。请注意引发了一个异常,这是因为在del tup tuple之后不再存在-

('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in 
      print tup;
NameError: name 'tup' is not defined

元组基本操作

元组对+和*运算符的响应类似于字符串;它们在这里也意味着串联和重复,只是结果是一个新的元组,而不是字符串。

实际上,元组会响应我们在上一章中对字符串使用的所有常规序列操作-

Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
(‘Hi!’,) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 1 2 3 Iteration

索引,切片和矩阵

因为元组是序列,所以索引和切片对元组的工作方式与对字符串的工作方式相同。假设以下输入-

L = ('spam', 'Spam', 'SPAM!')
Python Expression Results Description
L[2] ‘SPAM!’ Offsets start at zero
L[-2] ‘Spam’ Negative: count from the right
L[1:] [‘Spam’, ‘SPAM!’] Slicing fetches sections

没有封闭的分隔符

如以下简短示例所示,任何以逗号分隔的,没有标识符号的多个对象集(即列表的括号,元组的括号等)的编写都默认为元组-

现场演示

#!/usr/bin/python

print 'abc', -4.24e93, 18+6.6j, 'xyz';
x, y = 1, 2;
print "Value of x , y : ", x,y;

执行以上代码后,将产生以下结果-

abc -4.24e+93 (18+6.6j) xyz
Value of x , y : 1 2

内置元组功能

Python包含以下元组函数-

Sr.No. Function with Description
1 cmp(tuple1, tuple2)

Compares elements of both tuples.

2 len(tuple)

Gives the total length of the tuple.

3 max(tuple)

Returns item from the tuple with max value.

4 min(tuple)

Returns item from the tuple with min value.

5 tuple(seq)

Converts a list into tuple.