我觉得相比列表来说元组没有那么重要,但还是要会运用滴
定义:
由一系列变量组成的不可变 有序 序列容器(可存储任意类型数据)。
特点:占用连续内存空间,按需分配存储空间
说明:不可变:一但创建,不可以再添加/删除/修改元素 (很重要哦!)
元组适用于存储数据数量固定的数据。
元组的基本操作
创建元组
tuple01 = (10,20,30)
list01 = ['a','b','c']
tuple02 = tuple(list01)
定位
print(tuple01[0]) #10
print(tuple01[:2]) #(10,20)
遍历
for i in tuple01: #正序
print(tuple01[i])
for i in range(len(tuple01) -1,-1,-1): #倒序
print(tuple01[i])
特殊情况
tuple03 = 10,20,30 #小括号可以省略
tuple04 = (10,) #如果元组中只有一个元素,必须有逗号
小试牛刀一下叭
根据年月日,计算是这一年的第几天.
公式:前几个月总天数 + 当月天数
例如:5月10日
计算:31 29 31 30 + 10
#输入
date = input("请输入日期(如:2022/2/24):")
year,month,day = [int(date) for date in date.split('/')]
#判断输入数字是否符合实际情况
if year > 0 and 0 < month < 13 and 0 < day < 32:
total_day = day
tuple_day = (31,28,31,30,31,30,31,31,30,31,30,31)
#判断是否为闰年
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
total_day += 1
#计算
total_day += sum(tuple_day[:month - 1])
print(f'{year}-{month}-{day}是{year}的第{total_day}天')
else:
print('请输入正确日期')
关于元组的相关知识就差不多啦,菜孔孔会继续练习代码的,加油,冲冲 冲 冲冲!