gb_蓝桥杯python_基础语法_数据容器

元组的定义

定义一个元组使用一个原括号(),元素和之间用逗号,
即使只有一个元素,也需要加逗号:single_tuple = ("hello",)(否则会被认为是字符串)
变量名=(元素1,元素2,元素3...)

my_typle=(1,2,3,4,5)
print(my_typle)

元组的相关操作

1.index查找某个元素的下表

my_typle=(1,2,3,4,5)
print(my_typle.index(3))

2.count统计某个元素在元组中出现的次数

my_typle=(1,2,3,4,3)
print(my_typle.count(3))

3.len统计元组中元素个数

my_typle=(1,2,3,4,3)
print(len(my_typle))

元组中元素的遍历

for循环

my_typle=(1,2,3,4,3)
for element in my_typle:
    print(element)

while循环

my_typle=(1,2,3,4,3)
index=0
while index<len(my_typle):
    print(my_typle[index])
    index+=1

总结

元组 (Tuple) 是 Python 中一种有序、不可变的容器数据类型, 具有不可变性,用于存储一组可能不同类型的元素。

posted @ 2025-12-16 23:03  布丁黑全套  阅读(4)  评论(0)    收藏  举报