Python列表中某个元素的最后一次出现
在本文中,我们将看到在列表中找到元素的最后出现的不同方法。
让我们看看如何通过反转给定列表来查找元素的最后一次出现。请按照以下步骤编写代码。
初始化列表。
使用反向方法反向列表。
使用索引方法查找元素的索引。
元素的实际索引为len(list)-index-1。
打印最终索引。
示例
让我们看一下代码。
# initializing the list words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come'] element = 'sleep' # reversing the list words.reverse() # finding the index of element index = words.index(element) # printing the final index print(len(words) - index - 1)
如果运行上面的代码,则将得到以下结果。
输出结果
5
另一种方法是查找所有索引并从中获取最大值。
示例
让我们看一下代码。
# initializing the list words = ['eat', 'sleep', 'drink', 'sleep', 'drink', 'sleep', 'go', 'come'] element = 'sleep' # finding the last occurrence final_index = max(index for index, item in enumerate(words) if item == element) # printing the index print(final_index)
如果运行上面的代码,则将得到以下结果。
输出结果
5
结论
如果您对本文有任何疑问,请在评论部分中提及它们。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下