访问给定 Python 索引列表中的所有元素

pythonserver side programmingprogramming更新于 2025/8/14 20:28:17

我们可以使用 [] 括号和索引号访问列表的各个元素。但是当我们需要访问某些索引时,我们就不能应用此方法了。我们需要以下方法来解决这个问题。

使用两个列表

在此方法中,除了原始列表外,我们还将索引作为另一个列表。然后我们使用 for 循环遍历索引并将这些值提供给主列表以检索值。

示例

given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1,3,4]

# 打印列表
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))

# 使用列表推导式
res = [given_list[n] for n in index_list]

# 获取结果
print("Result list : " + str(res))

输出

运行上述代码得到以下结果 −

Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
List of Indices : [0, 1, 2, 3, 4]
Result list : ['Tue', 'Thu', 'Fri']

使用 map 和 geritem

除了使用上面的 for 循环,我们还可以使用 map 和 getitem 方法来获得相同的结果。

示例

given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1, 3,4]

# 打印列表
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))

# 使用列表推导式
res = list(map(given_list.__getitem__,index_list))

# 获取结果
print("Result list : " + str(res))

输出

运行上述代码得到以下结果 −

Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
List of Indices : [1, 3, 4]
Result list : ['Tue', 'Thu', 'Fri']

相关文章


有用资源