34 lines
838 B
Python
34 lines
838 B
Python
# 题目 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}")
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|