You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术问询:如何访问元组列表中的元组内部值及循环输出指定内容

访问元组内部值并循环遍历输出

嘿,这问题很好解决,我给你一步步讲明白!

首先,你已经知道用tuples[0]能拿到整个元组,那要取元组里的具体值,只需要再加一个索引就行——元组和列表一样是有序序列,可以用数字索引(从0开始)访问内部元素:

  • 拿第一个元组举例:tuples[0][0]会返回年龄41,tuples[0][1]会返回姓名'Mike'
  • 同理,tuples[2][1]就能拿到第三个元组里的'Sarah'

接下来是循环遍历并输出指定格式的内容,这里有两种常用写法,都很实用:

方法1:逐个提取元组元素

先遍历列表里的每个元组,再分别取出年龄和姓名:

tuples = [(41, 'Mike'), (29, 'Tom'), (28, 'Sarah'), (22, 'Jane'), (18, 'John')]

for person in tuples:
    age = person[0]
    name = person[1]
    print(f"They are {age} years old, and their name is {name}.")

方法2:元组拆包(更简洁推荐)

Python支持直接把元组的元素“拆”到变量里,这种写法可读性更高,代码也更清爽:

tuples = [(41, 'Mike'), (29, 'Tom'), (28, 'Sarah'), (22, 'Jane'), (18, 'John')]

for age, name in tuples:
    print(f"They are {age} years old, and their name is {name}.")

运行上面任意一段代码,都会输出:

They are 41 years old, and their name is Mike.
They are 29 years old, and their name is Tom.
They are 28 years old, and their name is Sarah.
They are 22 years old, and their name is Jane.
They are 18 years old, and their name is John.

因为你的列表已经按年龄排好序了,遍历的时候会保持这个顺序输出,完全符合你的需求~

内容的提问来源于stack exchange,提问作者Will.S89

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:38:34