获取具有给定索引的Python列表的子列表? [英] Getting a sublist of a Python list, with the given indices?
本文介绍了获取具有给定索引的Python列表的子列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Python列表,例如a = [0,1,2,3,4,5,6]
.我也有一个索引列表,例如b = [0,2,4,5]
.如何在b
中获得带有索引的a
元素列表?
I have a Python list, say a = [0,1,2,3,4,5,6]
. I also have a list of indices, say b = [0,2,4,5]
. How can I get the list of elements of a
with indices in b
?
推荐答案
您可以使用列表理解来获取该列表:
You can use list comprehension to get that list:
c = [a[index] for index in b]
print c
这等效于:
c= []
for index in b:
c.append(a[index])
print c
输出:
[0,2,4,5]
注意:
请记住,some_list[index]
是用于访问特定索引中的list
元素的符号.
Remember that some_list[index]
is the notation used to access to an element of a list
in a specific index.
这篇关于获取具有给定索引的Python列表的子列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文