元组 tuple
1. 元组定义
1.由一系列变量组成的不可变序列容器
2.不可变是指一旦创建,不可以对元素进行增删改查
2.元组的作用
1.元组和列表一样都可以存储一系列变量,由于列表会预留内存空间,所以可以增加元素
2.元组按需求分配内存,所以如果变量数量固定,建议使用元组,因为占用空间更小
3.应用: 变量交换的本质就是创建元祖:x,y = y,x 格式化字符串的本质就是创建元祖:”姓名:%s,年龄:%d %(tarena,15)“
month = int(input("请输入月份:"))
if month < 1 or month >12:
print("输入有误")
elif month == 2:
print("28天")
elif month == 4 or month ==6 or month ==9 or month == 11:
print("30天")
else:
print("31天")
#利用元祖优化代码
month = int(input("请输入月份:"))
if month < 1 or month >12:
print("输入有误")
else:
# 将每月的天数存入元组
day_of_month = (31,28,31,30,31,30,31,31,30,31,30,31)
print(day_of_month[month-1])
结果输出:
请输入月份:2
28天
请输入月份:2
28
一、元组基础操作
1.创建元组
创建空元组
元组名 = ()
元组名 = tuple()
创建非空元组
元组名 = (20,)
元组名 = (1,2,3)
元组名 = 100,200,300
# 创建空元组
tuple01 = (20,)
#具有默认值
tuple02 = (1,2,3)
# 列表-->元组
tuple01 = tuple(["a","b"])
print(tuple01)
# 元组-->列表
tuple01 = (1,2,3)
list01 = list(tuple01)
print(list01)
# 如果元组只有一个元素,构建方法如下
tuple02 = (100,)
print(type(tuple02))
2.获取元素
索引
tuple03 = ("a","b","c","d")
e01 = tuple03[1]
print(type(e01)) # str
# 可以直接将元组赋值给多个变量
tuple04 = (100,200)
a,b = tuple04
print(a)
print(b)
切片
tuple03 = ("a","b","c","d")
e02 = tuple02[-2:]
print(type(e02)) # tuple
3.遍历元组
正向遍历
for item in tuple04:
print(item)
反向遍历
for i in range(len(tuple04)-1,-1,-1):
print(i)