如何在Python 3.10中遍历二维数组,返回最高分竞争者的姓名与分数
遍历二维数组的几种实用方法
针对你给出的二维数组,这里提供几种常用的遍历方案:
1. 基础嵌套循环遍历
最直观的方式,外层循环逐个取出子数组,内层循环遍历子数组中的每个元素:
competitors = [["John", 11], ["Jenny", 13], ["Matthew", 3], ["Bev", 22], ["Claire", 12]] for person in competitors: for item in person: print(item)
2. 解构子数组元素遍历
因为每个子数组的结构固定(姓名+分数),可以直接解构元素,让代码更清晰易读:
for name, score in competitors: print(f"姓名:{name},分数:{score}")
3. 带索引的遍历
如果需要用到数组的位置索引,用enumerate就能同时拿到索引和对应元素:
for idx, (name, score) in enumerate(competitors): print(f"第{idx+1}位参赛者:{name},分数{score}")
内容的提问来源于stack exchange,提问作者English_Garfield
相关产品推荐
相关产品推荐

