python中元组的学习

元组


元组的概念

  • Tuple(元组)与列表相似,不同之处遭遇元组的元素不能修改
  • 元组表示多个元素组成的序列
  • 用于储存一串信息,数据之间使用,分隔
  • 元组用()定义
# 元组的创建
info_tuple = ("zhangsan",18,1.75)
info_tuple2 = (1,)  # 只有一个元素时要加一个逗号

tuple3 = tuple('hello')  # tuple():类型转换
tuple4 = tuple([3,4,5])  # 列表-->元组

元组操作

# 索引
print(tuple[-1])
# 切片
print(tuple[::-1])
# 计算元素个数
print(len(tuple))
# 取元组中最大值最小值
print(max(tuple),min(tuple))
# 删除元素del
del tuple()
print(tuple)

元组的常用方法

a=tuple.count('hello')
print(a)  # 应该输出tuple中hello的个数

b=tuple.index(2)
print(b)  # 应该输出2在tuple中的索引值

元组的遍历

# 方法一:
for i in tuple:
    print(i)

# 方法二:
for index,value in enumerate(tuple):
    print(inex,value)

#方法三:
for i in range(len(tuple)):
    print(i,tuple[i])
posted @ 2024-07-31 10:38  BingBing爱化学-04044  阅读(18)  评论(0)    收藏  举报