Files
2025PY/day13/03-练习.py
2025-05-22 16:50:44 +08:00

34 lines
838 B
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 题目 1添加元素并查找索引
# 有一个列表 fruits = ['apple', 'banana', 'cherry'],需要添加 'date' 和 'elderberry' 到列表末尾,然后找出 'cherry' 在列表中的索引。
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
fruits.append('elderberry')
index = fruits.index('cherry')
print(index)
# 题目 2添加元素并处理重复元素索引
# 有一个列表 numbers = [1, 2, 3, 2, 4, 2],添加数字 5 到列表末尾。然后找出数字 2 在列表中第一次出现的索引和最后一次出现的索引。
numbers = [1, 2, 3, 2, 4, 2]
numbers.append(5)
first_index = numbers.index(2)
last_index = len(numbers) - numbers[::-1].index(2) - 1
print(f"数字 2 第一次出现的索引是: {first_index}")
print(f"数字 2 最后一次出现的索引是: {last_index}")