访问 Python 中给定的索引列表中的所有元素
可以使用 [] 括号和索引号访问列表中的单个元素。但当我们需要访问某些索引时无法应用此方法。我们需要用以下方法来解决此问题。
使用两个列表
此方法中,我们会将原始列表与索引作为另一个列表。然后使用 for 循环来遍历索引并将这些值提供给主列表以检索值。
示例
given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1,3,4]
# printing the lists
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))
# use list comprehension
res = [given_list[n] for n in index_list]
# Get the result
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 和 getitem
除了使用上面的 for 循环外,还可使用 map 和 getitem 方法获得相同的结果。
示例
given_list = ["Mon","Tue","Wed","Thu","Fri"]
index_list = [1, 3,4]
# printing the lists
print("Given list : " + str(given_list))
print("List of Indices : " + str(index_list))
# use list comprehension
res = list(map(given_list.__getitem__,index_list))
# Get the result
print("Result list : " + str(res))输出
运行以上代码将得到以下结果 −
Given list : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] List of Indices : [1, 3, 4] Result list : ['Tue', 'Thu', 'Fri']
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP