Python通过索引选择列表中的元素

时间:2014-05-20 15:07:49

标签: python list indexing set

我在python中有一个列表,我希望从中获取一组索引并保存为原始列表的子集:

templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]

我想要这个:

   sublist=[[1,    4,    7,                      16,      19,20]]

作为一个例子。

我无法提前知道列表元素的内容是什么。我只有指数总是一样的。

这样做有单行方法吗?

5 个答案:

答案 0 :(得分:3)

使用operator.itemgetter

>>> templist = [[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]]
>>> import operator
>>> f = operator.itemgetter(0,3,6,15,18,19)
>>> sublist = [list(f(templist[0]))]
>>> sublist
[[1, 4, 7, 16, 19, 20]]

答案 1 :(得分:1)

你可以使用枚举的列表理解:

indices = [1,2,3]
sublist = [element for i, element in enumerate(templist) if i in indices]

答案 2 :(得分:1)

您可以使用列表理解:

indices = set([1,2,3])
sublist = [el for i, el in enumerate(orig_list) if i in indices]

或者您可以将索引存储在True / False列表中并使用itertools.compress

indices = [True, False, True]
sublist = itertools.compress(orig_list, indices)

答案 3 :(得分:1)

假设您知道要选择的索引是什么,它将起作用:

indices = [1, 4, 7, 16, 19, 20]
templist = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]]
sublist = []

for i in indices:
    sublist.append(templist[i])

这也可以用列表理解的形式表达 -

sublist = [templist[0][i] for i in indices]

答案 4 :(得分:0)

 mylist = ['A','B','C','D','E','F']
 idx = [0,1,3]
 [mylist[i] for i in idx]

['A','B','D']