Jack Arnestad
Jack Arnestad

Reputation: 1865

Subset items in list of list based on indices

I have a list like the following:

test = [['hi', 'hi2'], ['bye', 'bye2', 'by3']]

and would like to subset it based on another list of lists with the desired indices in it:

indices = [[0], [0, 2]] 

For a normal list of values and list of indices, it is easy to do:

[1d_list[i] for i in 1d_indices]

So I tried something similar for this list of lists, but it is not working

[[[t[i] for i in ii] for t in test] for ii in indices]

Could you please advise what is wrong?

The desired output for this part is

test_out = [['hi'], ['bye', 'by3']]

Also, how can I select the exact inverse of what is in indices?

For example, desired output would be:

test_out_2 = [['hi2'], ['bye2']]

Thanks! Jack

Upvotes: 0

Views: 46

Answers (1)

Ajax1234
Ajax1234

Reputation: 71451

You can use zip with enumerate:

test = [['hi', 'hi2'], ['bye', 'bye2', 'by3']]
indices = [[0], [0, 2]] 
new_test = [[a for i, a in enumerate(c) if i in b] for c, b in zip(test, indices)]

Output:

[['hi'], ['bye', 'by3']]

Upvotes: 2

Related Questions