元组
作者:互联网
不能进行增.删.改,其余的规则和列表一样,元组用的不多.
格式:(元素1,元素2...)
只能进行查询,不能对其进行增.删.改
元组(索引)
tuple1 = ("zhang", 18, 15.87, True) print(tuple1) print(type(tuple1)) print(tuple1[0]) # tuple1[0] = 6 TypeError: 'tuple' object does not support item assignment tuple1 = (50) print(type(tuple1)) # <class 'int'> tuple1 = (50,) # 如果元组中只有一个元素时,会自动进行类型推导,需要加个,号 print(type(tuple1))
应用场景1:元组是自动组包的默认类型
a = 10, 20 # 如果把多个值赋值给一个变量时,它会自动把多个数据组包成元组 print(a) # (10,20) print(type(a)) # tuple tuple1 = (10, 20, 30) # ValueError: too many values to unpack (expected 2) a, b, c = tuple1 # 如果一个元组赋值给多个变量时,如果元组中元素个数和变量数一致,会自动赋值给每个变量,解包,拆包 print(a) print(b) print(c) # 组包是应用最多的地方
不使用中间变量交换a,b的值:
a = 10 b = 20 a,b = b,a
应用场景2:字符串格式
price = 7.5 weight = 8.0 tuple1 = (price, weight) print("单价:%.2f,重量:%.1f" % (price, weight)) print("单价:%.2f,重量:%.1f" % tuple1)
应用场景3:保证数据的安全性
list1 = [10, 20, 30] # 类型转换: 转换成元组 tuple1 = tuple(list1) print(tuple1)
标签:10,%.,20,元组,tuple1,print 来源: https://www.cnblogs.com/huaibin/p/12095485.html