元组(tuple)
和列表是类似的
列表是可变的有序序列;元组是不可变的有序序列
什么时候使用元组? 数据元素确定 且不会再发生变化 就可以使用元组
31天的月份 1 3 5 7 8 10 12
元组的数据标记是(), 列表的是[]
提高运算符优先级的时候 也是使用()
注意: 一元组[元组中有1个数据]定义的时候 元素后面必须加上逗号, 否则会识别成提高表达式优先级 就不是元组类型的
nums = (11) nums1 = (11,) print(type(nums), type(nums1)) # <class 'int'> <class 'tuple'>
判断输入的月份是否有30天
month = int(input('请输入月份:')) year = int(input('请输入年份:')) if month == 4 or month == 6 or month == 9 or month == 11: print(month, '有30天') if month in (4, 6, 9, 11): print(year, '年', month, '月有30天') elif month in (1, 3, 5, 7, 8, 10, 12): print(year, '年', month, '月有31天') else: if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(year, '年', month, '月有29天') else: print(year, '年', month, '月有28天')
nums = (11, 23, 45, 67, 87, 29, 45) print(nums[:3]) # nums[0] = 19 不支持元素被修改的 # TypeError: 'tuple' object does not support item assignment print(nums[-1])
当给一个变量 赋值的时候使用逗号分隔开多个数据 这个多个数据进行打包的操作 打包成元组赋值给变量
values = 11, 23, 45, 61, 72, 38, 49 print(type(values)) # <class 'tuple'>
解包 把一个容器中多个数据赋值给多个变量
a, b = 11, 23 print(a, b)
将位置和该位置的元素组合成元组 放在一个新的容器A中 这个A就是一个二维容器
for item in enumerate([12, 34, 56, 71]): print(item) # (0, 12)