Tuple

Tuple


什么是Tuple?

  • Tuple是python对象组成的序列,此序列内容不可变,即不能编辑元素,这一点和List不同;
  • 定义Tuple使用逗号将对象分割,或者将分割的对象放在括号内;
tup1 = ("physics", "chemistry", 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7)
tup3 = "a", "b", "c", "d"# print result ('a','b','c','d')
  • 空tuple
tup1 = () 
print(type(tup1)) # print <class 'tuple'>
print(tup1) #print ()
  • 单值tuple
# 注意需要在元素后面加逗号,
tup1 = (50,)
  • 与索引一样,tuple索引从0开始,可以切断,级联等

如何获取Tuple的值?

  • 可以通过索引的方式获取Tuple内的值
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print("tup1[0]: ", tup1[0]) # print tup1[0]: physics
# print 第2到5个数据
print("tup2[1:5]: ", tup2[1:5]) # print tup2[1:5]: (2,3,4,5)

更新Tuple

  • Tuple是不可变的,意味着tuple内对象的值不能更新或修改,但是可以通过获取tuple部分对象创建新的tuple
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')

删除Tuple元素

  • 删除tuple单个元素是不可能的,只能用del语句删除整个tuple
tup = ('physics', 'chemistry', 1997, 2000);
print(tup)
del tup
print "After deleting tup : ";
print(tup)
  • 执行结果会显示
NameError: name 'tup' is not defined

Tuple的基本操作符

  • 与字符串类似,tuple响应+,*的操作符,表示结合,重复;不同的是结果是新的tuple
  • 事实上,tuple响应以下所有的操作
Python ExpressionResultDescription
len((1,2,3))3length
(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)TrueMembership
for x in (1, 2, 3): print x1 2 3Iteration

索引切片矩阵

  • 因为tuple是序列,因此适用于string的索引,切片,矩阵一样适用于tuple
L = ('spam', 'Spam', 'SPAM!')
Python ExpressionResultDescription
L[2]‘SPAM!’Offsets start at zero
L[-2]‘Spam’Negative: count from the right
L[1:](‘Spam’, ‘SPAM!’)Slicing fetches sections

无封闭分隔符

  • 任何一组以逗号分隔的的多个对象,写入时不带标识符号,即List不带[],tuple不带(),都默认为tuple
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

Tuple的内联方法

Sr.No.Function with Description
1cmp(tuple1, tuple2) Compares elements of both tuples.
2len(tuple) Gives the total length of the tuple
3max(tuple) Returns item from the tuple with max value.
4min(tuple) Returns item from the tuple with min value.
5tuple(seq) Converts a list into tuple.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值