python——元组
元组的概念
Python的元组与列表类似,不同之处在于元组的元素不能修改。
元组使用小括号,列表使用方括号。
元组创建很简单,只需要在括号中添加元素,并使用逗号隔开即可。
元组的创建
tup1 = (‘physics’, ‘chemistry’, 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup1 = () #创建空元组
注意:元组中只包含一个元素时,需要在元素后面添加逗号
tup1 = (50,)
元组与字符串类似,下标索引从0开始,可以进行截取,组合等。
这里是引用
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)
代码副本:
#创建元组
tuple4=(1,2,3,4,5)
print(tuple4)#结果:(1, 2, 3, 4, 5)
print(type(tuple4))#type()返回元素类型 结果:<class 'tuple'>
tuple1=(1)
print(tuple1)#结果:1
print(type(tuple1))#结果:<class 'int'>
tuple2=(1,)
print(tuple2)#结果:(1,)
print(type(tuple2))#结果:<class 'tuple'>
list=[1,2,3]
tuple3=tuple(list)#将list转换为tuple型
print(tuple3)
print(type(tuple3))