首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[教程]Python遍历数组同时获取索引,轻松掌握技巧

发布于 2025-12-16 09:30:46
0
802

引言在Python中,遍历数组(或列表)是常见的基础操作。有时候,我们不仅需要访问数组中的元素,还需要知道每个元素对应的索引。Python提供了多种方法来实现这一需求,本文将详细介绍几种常用的技巧。使...

引言

在Python中,遍历数组(或列表)是常见的基础操作。有时候,我们不仅需要访问数组中的元素,还需要知道每个元素对应的索引。Python提供了多种方法来实现这一需求,本文将详细介绍几种常用的技巧。

使用for循环遍历数组并获取索引

最简单的方法是使用for循环遍历数组,同时使用内置的enumerate函数来获取索引。

arr = [10, 20, 30, 40, 50]
for index, value in enumerate(arr): print(f"Index: {index}, Value: {value}")

输出结果:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

使用while循环遍历数组并获取索引

除了for循环,我们还可以使用while循环结合索引来遍历数组。

arr = [10, 20, 30, 40, 50]
index = 0
while index < len(arr): value = arr[index] print(f"Index: {index}, Value: {value}") index += 1

输出结果:

Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30
Index: 3, Value: 40
Index: 4, Value: 50

使用列表推导式遍历数组并获取索引

列表推导式是一种高效且简洁的遍历数组的方法。结合enumerate函数,我们可以轻松获取索引和值。

arr = [10, 20, 30, 40, 50]
result = [(index, value) for index, value in enumerate(arr)]
print(result)

输出结果:

[(0, 10), (1, 20), (2, 30), (3, 40), (4, 50)]

总结

在Python中,遍历数组并获取索引的方法有很多种。选择合适的方法取决于你的具体需求和偏好。本文介绍了使用for循环、while循环和列表推导式遍历数组并获取索引的技巧,希望对你有所帮助。

评论
一个月内的热帖推荐
csdn大佬
Lv.1普通用户

452398

帖子

22

小组

841

积分

赞助商广告
站长交流