从列表中的 Python 元组中访问第 n 个元素
pythonserver side programmingprogramming更新于 2025/12/25 19:56:17
Python 列表可以包含元组作为其元素。在本文中,我们将探讨如何从元组中访问作为给定元组中元素存在的每个第 n 个元素。
使用索引
我们可以设计一个 for 循环来访问列表中的元素,并将 in 子句应用于第 n 个索引。然后我们将结果存储到新列表中。
示例
Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]
# 给定列表
print("Given list: ",Alist)
# 使用索引
res = [x[1] for x in Alist]
print("The 1 st element form each tuple in the list: \n",res)
输出
运行上述代码得到以下结果 −
Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
['3 pm', '12pm', '9 am', '6 am']
使用 itemgetter
operator 模块中的 itegetter 函数可以从给定的可迭代对象中获取每个项目,直到搜索到可迭代对象的末尾。在这个程序中,我们从给定的列表中搜索索引位置 2,并应用 map 函数将相同的函数反复应用于 itemgetter 函数结果中的每个结果。最后我们将结果存储为列表。
示例
from operator import itemgetter
Alist = [('Mon','3 pm',10),('Tue','12pm',8),('Wed','9 am',8),('Thu','6 am',5)]
#Given list
print("Given list: ",Alist)
# 使用 itemgetter
res = list(map(itemgetter(2), Alist))
print("The 1 st element form each tuple in the list: \n",res)
输出
运行上述代码得到以下结果 −
Given list: [('Mon', '3 pm', 10), ('Tue', '12pm', 8), ('Wed', '9 am', 8), ('Thu', '6 am', 5)]
The 1 st element form each tuple in the list:
[10, 8, 8, 5]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

