关于人工智能:32-元组Tuple

3次阅读

共计 2248 个字符,预计需要花费 6 分钟才能阅读完成。

接下来咱们将学习 Python 数据结构之一:元组(Tuple)。元组与列表相似,它也是一个有序的元素汇合。但元组与列表的要害区别在于元组是 不可变 的,这意味着您不能批改、增加或删除元素。

1. 创立元组

创立元组的最简略办法是应用圆括号 () 并用逗号分隔元素。例如:

numbers = (1, 2, 3, 4, 5)
print(numbers)  # (1, 2, 3, 4, 5)

fruits = ("apple", "banana", "orange")
print(fruits)  # ('apple', 'banana', 'orange')

另一种创立元组的办法是应用内置的 tuple() 函数:

empty_tuple = tuple()
print(empty_tuple)  # ()

another_tuple = tuple("hello")
print(another_tuple)  # ('h', 'e', 'l', 'l', 'o')

2. 拜访元组元素

与列表相似,您能够通过索引拜访元组中的元素。请留神,Python 中的索引是从 0 开始的。例如:

fruits = ("apple", "banana", "orange")

first_fruit = fruits[0]
print(first_fruit)  # apple

second_fruit = fruits[1]
print(second_fruit)  # banana

last_fruit = fruits[-1]
print(last_fruit)  # orange

3. 元组不可变性

如前所述,元组是不可变的。这意味着您不能批改元组中的元素。尝试批改元组中的元素将导致TypeError

fruits = ("apple", "banana", "orange")

# 以下代码会引发谬误
fruits[0] = "grape"

只管元组自身不可变,但如果元组蕴含可变对象(如列表),则这些对象依然能够批改。

4. 元组切片

与列表相似,您也能够对元组进行切片。切片操作应用冒号 : 分隔起始和完结索引。例如:

numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

first_three = numbers[:3]
print(first_three)  # (0, 1, 2)

middle_three = numbers[3:6]
print(middle_three)  # (3, 4, 5)

last_three = numbers[-3:]
print(last_three)  # (7, 8, 9)

5. 元组遍历

要遍历元组中的元素,能够应用 for 循环:

fruits = ("apple", "banana", "orange")

for fruit in fruits:
    print(fruit)

输入:

apple
banana
orange

6. 元组解包

元组解包(unpacking)是一种将元组中的元素调配给多个变量的办法。例如:

coordinate = (3, 4)

x, y = coordinate
print(x)  # 3
print(y)  # 4

请留神,解包时变量的数量必须与元组中的元素数量雷同,否则会引发ValueError

7. 元组长度、最大值和最小值

要获取元组的长度(元素数量),能够应用 len() 函数:

fruits = ("apple", "banana", "orange")

length = len(fruits)
print(length)  # 3

要获取元组中的最大值和最小值,能够应用 max()min()函数:

numbers = (3, 1, 4, 1, 5, 9, 2, 6, 5)

max_number = max(numbers)
print(max_number)  # 9

min_number = min(numbers)
print(min_number)  # 1

8. 元组合并

要将两个元组合并为一个新元组,能够应用 + 运算符:

fruits1 = ("apple", "banana", "orange")
fruits2 = ("grape", "pineapple", "lemon")

combined_fruits = fruits1 + fruits2
print(combined_fruits)  # ('apple', 'banana', 'orange', 'grape', 'pineapple', 'lemon')

9. 元组反复

要将元组中的元素反复 n 次,能够应用 * 运算符:

repeated_fruits = ("apple", "banana") * 3
print(repeated_fruits)  # ('apple', 'banana', 'apple', 'banana', 'apple', 'banana')

10. 元组元素计数和查找索引

要计算元组中某个元素呈现的次数,能够应用 count() 办法:

numbers = (1, 2, 3, 2, 4, 5, 2)

count_2 = numbers.count(2)
print(count_2)  # 3

要找到元组中某个元素第一次呈现的索引,能够应用 index() 办法:

numbers = (1, 2, 3, 2, 4, 5, 2)

index_2 = numbers.index(2)
print(index_2)  # 1

请留神,如果元素不存在于元组中,index()办法会引发ValueError

至此,咱们曾经具体解说了 Python 元组的基本概念和操作。心愿这些内容对您有所帮忙。请务必多做练习,以便更好地把握这些常识。
举荐浏览:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

正文完
 0