Python selecting elements in a list by indices

一个人想着一个人 提交于 2020-08-10 04:59:24

问题


I have a list in python that I want to get the a set of indexes out of and save as a subset of the original list:

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

and I want this:

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

as an example.

I have no way of knowing ahead of time what the contents of the list elements will be . All I have is the indices that will always be the same.

Is there a single line way of doing this?


回答1:


Assuming you know what the indices to be selected are, it would work something like this:

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])

This can also be expressed in the form of a list comprehension -

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



回答2:


Using 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]]



回答3:


you can use list comprehension with enumerate:

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



回答4:


You can use list comprehension:

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

Or you can store indices in a list of True/False and use itertools.compress:

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


来源:https://stackoverflow.com/questions/23763591/python-selecting-elements-in-a-list-by-indices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!