Python学习之路-----元组

元组定义

元组是Python中高级数据类型的一种,它的定义方法和列表相似,只需要将[]换成()即可。

tuple_test = (1,2,3,6.6534156,"ABC")

基本特性

元组和列表一样,其数据项数和索引之间存在差1的关系,同样可以使用print(元组名[索引])输出指定的值,同样可以使用type()获得类型。唯一不同的是,元组一经定义其数据就不能改变,只能进行查询操作。因此元组只有index(),len(),count()等方法。

元组与字符串的相似性而导致的差异

在定义字符串的时候需要用”“,但是还可以在”“外加上()。

str1 = "ABC"
print("str1:",str1)
print("type(str1):",type(str1))

str2 = ("ABC")
print("str2:",str2)
print("type(str2):",type(str2))

结果:

str1: ABC
type(str1): <class 'str'>
str2: ABC
type(str2): <class 'str'>


当元组只有一个字符串的数据时,它的形式就跟上面的str2的形式一样,但是这个时候实际是字符串类型的,若想保持元组类型,需要在后面加一个逗号。

tuple1 = ("ABC")
print("tuple1:",tuple1)
print("type(tuple1):",type(tuple1))

tuple2 = ("ABC",)
print("tuple2:",tuple2)
print("type(tuple2):",type(tuple2))

结果:

tuple1: ABC
type(tuple1): <class 'str'>
tuple2: ('ABC',)
type(tuple2): <class 'tuple'>

元组的使用场景

1.如果把多个值附给一个变量时,他就会自动组包,成为一个元组类型。

a = 10,20,30
print(type(a)) # <class 'tuple'>
print(a) #(10, 20, 30)

2.有自动组包,也可以自动解包。但是此时变量个数必须与元组个数相等。

a = 10,20,30
A, B, C = a
print(A)   # 10
print(B)   # 20
print(C)   # 30

3.当执行tuple(列表名)后,会将列表中数据依次取出并赋给一个元组,但是列表本身还是列表;

list1 = ["zhangsan","lisi","wangwu"]
result = tuple(list1)   
print(result)   # ('zhangsan', 'lisi', 'wangwu')
print(type(list1)) # <class 'list'>

   

猜你喜欢

转载自blog.csdn.net/shen_chengfeng/article/details/80558016