在给定的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']
使用映射和geritem
除了使用上面的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']
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练