Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python selecting elements in a list by indices [duplicate]

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?

like image 336
testname123 Avatar asked Nov 14 '25 18:11

testname123


2 Answers

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]]
like image 130
falsetru Avatar answered Nov 17 '25 09:11

falsetru


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[0][i])

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

sublist = [templist[0][i] for i in indices]
like image 39
Chaitanya Nettem Avatar answered Nov 17 '25 08:11

Chaitanya Nettem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!